/**
* 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* pre=head;
ListNode* pos=head->next;
ListNode* ppre=NULL;
bool first = true;
while(pos) {
pre->next=pos->next;
pos->next=pre;
if (first) {
head = pos;
first = false;
} else {
//ppre=pre;
ppre->next = pos;
}
ppre = pre;
pre=pre->next;
if (pre) {
pos=pre->next;
} else {
pos=NULL;
}
}
return head;
}
};
* 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* pre=head;
ListNode* pos=head->next;
ListNode* ppre=NULL;
bool first = true;
while(pos) {
pre->next=pos->next;
pos->next=pre;
if (first) {
head = pos;
first = false;
} else {
//ppre=pre;
ppre->next = pos;
}
ppre = pre;
pre=pre->next;
if (pre) {
pos=pre->next;
} else {
pos=NULL;
}
}
return head;
}
};