/**
* 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) return NULL;
ListNode* prev = NULL;
ListNode* cur = head;
ListNode* next = NULL;
while (cur)
{
if (cur->next)
{
next = cur->next;
cur->next = next->next;
next->next = cur;
if (prev)
prev->next = next;
else
head = next;
prev = cur;
cur = cur->next;
}
else
break;
}
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
ListNode** curNext = &head;
while (NULL != *curNext && NULL != (*curNext)->next)
{
ListNode* temp = (*curNext)->next;
(*curNext)->next = (*curNext)->next->next;
temp->next = *curNext;
*curNext = temp;
curNext = &(*curNext)->next->next;
}
return head;
}
};
120

被折叠的 条评论
为什么被折叠?



