实现一
public class Node{
public int value;
public Node next;
}
//反转单链表
public static Node reverseList(Node head) {
Node next = null;//指向当前节点的后继
Node pre = null;//指向当前节点的前驱
while (head != null) {
next = head.next;
//当前节点的后驱指向前驱
head.next = pre;
pre = head;
//处理下一个节点
head = next;
}
return pre;
}
实现二
//用递归的方法反转链表
public static Node reverseList(Node head){
if (head == null || head.next == null) {
return head;
}
//递归反转子lian链表
Node newList = reverseList(head.next);
head.next.next = head;
head.next = null;
return newList;
}