1. 程式人生 > >LeetCode 206. 反轉連結串列 遞迴解決

LeetCode 206. 反轉連結串列 遞迴解決

反轉一個單鏈表。

示例:

輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL

進階:
你可以迭代或遞迴地反轉連結串列。你能否用兩種方法解決這道題?

注意head是有值的

class Solution {
    void Insert(ListNode head,ListNode p){
    if(p.next==null)
    {
        return;
    }
    Insert(head,p.next);
    p.next.next=p;//反轉節點
    p.next=null;//第一個節點反轉後其後繼應該為NULL
    }
    public ListNode reverseList(ListNode head) {
        if(head==null){
            return head;
        }
        ListNode tmp = head;
        while(tmp.next!=null){
            tmp=tmp.next;
        }
        Insert(tmp,head);
        return tmp;
    }
}