/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
输入一个链表,反转链表后,输出链表的所有元素。
循环实现,代码如下:
public class Circle_Reverse {
public ListNode ReverseList(ListNode head) {
if(null==head)
return head;
ListNode pre = head;
ListNode cur = head.next;
ListNode next;
while(null!=cur){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
head.next=null;
head=pre;
return head;
}
}
递归实现
public class Recursion_Reverse {
public ListNode ReverseList(ListNode head) {
if(null==head||null==head.next)
return head;
ListNode reverseHead = ReverseList(head.next);
head.next.next = head;//head.next的下一个节点为head(实现反转)
head.next = null;
return reverseHead;
}
}