public class ReverseList {
public static void main(String[] args) {
ListNode head = new ListNode(0);
head.next = new ListNode(1);
head.next.next = new ListNode(2);
head.next.next.next = new ListNode(3);
ListNode p = head.next;
showList(p);
p = reverseList(head);
showList(p);
p = reverse(p);
showList(p);
}
public static void showList(ListNode p){
while(p!=null){
System.out.print(p.val+" ");
p = p.next;
}
System.out.println();
}
public static ListNode reverseList(ListNode H){
if (H == null || H.next == null) //链表为空或者仅1个数直接返回
return H;
ListNode p = H.next;
ListNode pre = null;
while (p != null) //一直迭代到链尾
{
ListNode tmp = p.next; //暂存p下一个地址,防止变化指针指向后找不到后续的数
p.next = pre; //p->next指向前一个空间
pre = p; //新链表的头移动到p,扩长一步链表
p = tmp; //p指向原始链表p指向的下一个空间
}
return pre;
}
public static ListNode reverse(ListNode node){
ListNode prev = null;
ListNode next = null;
while(node!=null){
next = node.next;
node.next = prev;
prev = node;
node = next;
}
return prev;
}
}