leetcode 14: 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.


keypoints:1, head is special case, solve it before going to a loop.

2. after swap nodes, p and q's positions have been changed, since it's a linked list, redefine q at front of new loop. 



/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(head==NULL || head->next==NULL) return head;
        
        ListNode* p=head, *q=head->next;
        
        p->next = q->next;
        q->next = p;
        head = q;
        
        ListNode * pre = p;
        p=p->next;

        while(p!=NULL && p->next !=NULL) {
            q=p->next;
            
            p->next = q->next;
            q->next = p;
            pre->next = q;
            
            pre = p;
            p=p->next;
        }
        return head;
    }
};


posted @ 2012-12-25 00:11  西施豆腐渣  阅读(126)  评论(0编辑  收藏  举报