Swap Nodes in Pairs

题目:

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

Example

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

分析:

这道题目没什么技巧,注意用1->2->3->4->N的例子验证一下就很好。

解法:

class Solution {
public:
    /**
     * @param head a ListNode
     * @return a ListNode
     */
    ListNode* swapPairs(ListNode* head) {
        // Write your code here
        if (head == NULL || head->next == NULL) {
            return head;
        }

        ListNode dummy(-1);
        dummy.next = head;

        ListNode* prev = &dummy;
        ListNode* curr;
        ListNode* next;

        while (prev->next != NULL && prev->next->next != NULL) {
            curr = prev->next;
            next = prev->next->next;

            curr->next = next->next;
            next->next = curr;
            prev->next = next;

            prev = curr;
        }
        return dummy.next;
    }
};

results matching ""

    No results matching ""