反转链表
import java.util.Arrays;
import java.util.List;
import org.springframework.util.CollectionUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
/**
* 反转链表
*
* @author qhong
* @date 2022/12/20 09:11
**/
@Slf4j
public class ReverseLinkedListDemo {
public static void main(String[] args) {
Node head = createLinkedNode(Arrays.asList(1, 2, 3, 4, 5, 6));
printLinkedNode(head);
printLinkedNode(reverseList(head));
// printLinkedNode(reverse(head));
}
/**
* 使用遍历的方式
*
* @param node
* @return
*/
public static Node reverseList(Node node) {
Node pre = null;
Node next = null;
while (node != null) {
next = node.next;
node.next = pre;
pre = node;
node = next;
}
return pre;
}
/**
* 使用递归的方式
*
* @param head
* @return
*/
public static Node reverse(Node head) {
if (head == null || head.next == null)
return head;
Node temp = head.next;
Node newHead = reverse(head.next);
temp.next = head;
head.next = null;
return newHead;
}
static class Node {
public int value;
public Node next;
public Node(int data) {
this.value = data;
}
}
/**
* 创建链表,数组转链表
*
* @param list
* @return
*/
public static Node createLinkedNode(List<Integer> list) {
if (CollectionUtils.isEmpty(list)) {
return null;
}
Node head = new Node(list.get(0));
Node temp = head;
for (int i = 0; i < list.size() - 1; i++) {
Node next = new Node(list.get(i + 1));
temp.next = next;
temp = next;
}
return head;
}
/**
* 打印链表
*
* @param head
*/
public static void printLinkedNode(Node head) {
if (head == null) {
return;
}
List<String> arr = Lists.newLinkedList();
while (true) {
arr.add(String.valueOf(head.value));
head = head.next;
if (head == null) {
break;
}
}
log.info("linkedNodeList:{}", arr);
}
}
参考:
如何k个一组反转链表
理解单链表的反转(java实现)