1. 程式人生 > >leetcode 連結串列

leetcode 連結串列

連結串列結構

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

 

leetcode 206

反轉一個單鏈表。

示例:

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

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

 

思路:

迭代

設定兩個指標(new_head和next),new_head始終使其指向新連結串列的頭結點,next始終使其指向待反轉連結串列的頭結點。

步驟圖示如下(渣繪)

程式碼如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if((head==nullptr)||(head->next==nullptr))
            return head;
        
        ListNode * new_head=nullptr,*next=nullptr;
        while(head){
            //next指向待排序連結串列的頭結點
            next=head->next;
            //令被拆下來的節點的next指標指向新連結串列的頭結點
            head->next=new_head;
            //移動new_head,使其保持指向新連結串列的頭結點
            new_head=head;
            //使head指向待排序連結串列的頭結點
            head=next;
        }
        return new_head;
    }
};

 

遞迴

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *helper(ListNode *head) {
        ListNode *newHead =nullptr;
        if((head==NULL)||(head->next==NULL))
            return head;
        newHead = helper(head->next);
        head->next->next=head;
        head->next=NULL;
        return newHead;
    }
    
    ListNode* reverseList(ListNode* head) {
        if((head==nullptr)||(head->next==nullptr))
            return head;
        
        ListNode * tail=head;
        while(tail->next){
            tail=tail->next;
        }
        
        helper(head);
        return tail;
    }
};