Swap Nodes in Pairs

Jin Shang bio photo By Jin Shang

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

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example:

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

Solution:

Simple implementation

/**
 * 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) {
        ListNode* dummy = new ListNode(0);
        ListNode* prev = dummy;
        ListNode* cur = head;
        ListNode* next;
        dummy->next = head;
        while(cur){
            if(next = cur->next){
                prev->next = next;
                cur->next = next->next;
                next->next = cur;
                
                prev = cur;
                cur = cur->next;
            }
            else{
                break;
            }
        }
        return dummy->next;
    }
};