1. 程式人生 > >leetcode#24 Swap Nodes in Pairs

leetcode#24 Swap Nodes in Pairs

null cpp 循環 def 使用 class ret 內部 2個

給定一個鏈表,兩兩交換其中相鄰的節點,並返回交換後的鏈表。

示例:

給定 1->2->3->4, 你應該返回 2->1->4->3.
說明:

你的算法只能使用常數的額外空間。
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        //如果首節點之前有一個結點h,那就好了,我們交換第1、2個結點,再前進2次,交換3、4個結點
        //我們可以創造這個結點,也可以先交換1,2結點,讓這個結點指向新的第2個結點。這裏我用的是第2種辦法
        if(!head||!head->next) return head;//保證有兩個結點
        auto h=head;
        auto temp=h->next->next;
        head=h->next;
        h->next->next=h;
        h->next=temp;
       //現在head:2.。。。21345//h指向1,現在我們可以交換1的後面兩個,然後執行循環
        while(h->next&&h->next->next)//後2個結點存在
        {
            auto temp=h->next->next->next;//3
            auto t=h->next->next;
            h->next->next->next=h->next;
            h->next->next=temp;
            h->next=t;    
            h=h->next->next;
        }
        return head;
    }
};

leetcode#24 Swap Nodes in Pairs