反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
非递归方法:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode p0=head;
ListNode pre=null;
while(p0!=null){
ListNode p1=p0.next;
p0.next=pre;
pre=p0;
p0=p1;
}
return pre;
}
}
递归方法:
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
}
递归方法的理解: