[LeetCode] 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.

解题思路:

链表中1,2交换,3,4交换,5,6交换。这里注意一下起点,同时交换时候注意顺序即可。

/**
 * 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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(head == NULL || head -> next == NULL)
            return head;
            
        ListNode *root = NULL, *last = NULL, *first = head, *second = NULL, *tmp = NULL;
        while(first != NULL)
        {
            if(first -> next == NULL) break;
            second = first -> next;
            if(last == NULL)
            {
                root = second;
                tmp = second -> next;
                second -> next = first;
                first -> next = tmp;
                last = first;
                first = tmp;
                continue;
            }
            
            tmp = second -> next;
            last -> next = second;
            second -> next = first;
            first -> next = tmp;
            last = first;
            first = tmp;
        }
        return root;
    }
};

 

posted @ 2013-11-10 22:27  xchangcheng  阅读(247)  评论(0编辑  收藏  举报