Doing something you intrinsically are enthusiastic with.

2016年10月1日 星期六

Leetcode-Swap nodes in pair

下午1:40 Posted by Unknown No comments
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.
Subscribe to see which companies asked this question
----------------------------------------------------------------------------------------
Solution:
The dummy node is used to keep the swap_pair function work in consistent way at the 
very beginning. In other words, to satisfy the function at the very first initialization state.

Noted that we need to pass the pointer by reference so that the structure 
of the list will actually change.

class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
        head = dummy;
        while(head) head = swapNodes(head->next);
        head = dummy->next;
        delete dummy;
        return head;
    }
    
    ListNode *swapNodes(ListNode *&head) {
        if(!head || !head->next) return NULL;
        ListNode *tail = head;
        ListNode *nextHead = head->next->next;
        head = head->next;
        head->next = tail;
        tail->next = nextHead;
        return tail;
    }
};



0 意見:

張貼留言