Tuesday, August 4, 2015

024 - Swap Nodes in Pairs

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.
Hide Tags
Linked List
Hide Similar Problems
(H) Reverse Nodes in k-Group

但就这个in pairs翻转而言,很简单,
但这里的算法并不通用,对于后面提到的 翻转K个,可能要麻烦点,还没多想。

/**
* 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(0);
        dummy.next = head;
        if(head && head->next)
        {
            ListNode* oddd = head;
            ListNode* even = head->next;
            ListNode* prev = &dummy;
            while(oddd && even)
            {
                oddd->next = even->next;
                even->next = oddd;
                prev->next = even;
               
                prev = oddd;
                oddd = oddd->next;
                even = (NULL == oddd) ? NULL : oddd->next;
            }
        }
        return dummy.next;
    }
};

4 ms.

No comments:

Post a Comment