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.

 

/**
 * 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) {
        if(!head||!head->next)
            return head;
        //申请哨兵节点
        ListNode *h = (ListNode*)malloc(sizeof(struct ListNode));
        h->next=head;
        ListNode *s,*p,*q,*tmp;
        s=h;
        //两个节点中,p作为第一个节点,s是p前一个节点
        p=s->next;
        while(p){
            //q作为第二个节点
            q=p->next;
            if(!q)
                break;
            p->next=q->next;
            s->next=q;
            q->next=p;
            
            s=p;
            p=p->next;
        }
        p=h->next;
        free(h);
        return p;
    }
};

 






 

posted @ 2014-12-08 19:23  bingtel  阅读(136)  评论(0编辑  收藏  举报