24. Swap Nodes in Pairs

題目

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

分析

假設(shè)有連續(xù)的4個(gè)節(jié)點(diǎn)A->B->C->D,其中A為已經(jīng)交換過(guò)的上一輪的節(jié)點(diǎn)。則一輪交換后為A->C->B->D。運(yùn)用鏈表的操作方法實(shí)現(xiàn)這些節(jié)點(diǎn)關(guān)系的改變即可。

實(shí)現(xiàn)

/**
 * 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) {
        if(head==NULL || head->next==NULL) return head;
        ListNode dummy(-1);
        ListNode *p=&dummy, *tmp;
        dummy.next = head;
        while(p!=NULL && p->next!=NULL && p->next->next!=NULL){
            tmp = p->next->next;
            p->next->next = tmp->next;
            tmp->next = p->next;
            p->next = tmp;
            p = p->next->next;
        }
        return dummy.next;
    }
};

思考

對(duì)于這題來(lái)說(shuō),使用三個(gè)指針代碼會(huì)簡(jiǎn)潔一些。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容