LeetCode --- Swap Nodes in Pairs

来源:互联网 发布:淘宝论文的代写哪家好 编辑:程序博客网 时间:2024/05/24 06:50

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.

My Submitted Code

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {private:public:    ListNode *swapPairs(ListNode *head) {        if(!head || !head->next){            return head;        }        ListNode *prev;        ListNode *p1;        ListNode *p2;        p1=head;        prev=head;        do{            p2=p1->next;            p1->next=p2->next;            p2->next=p1;            if(prev!=head)                prev->next=p2;            else                head=p2;            prev=p1;            p1=p1->next;        }while(p1 && p1->next);        return head;    }};
0 0