题目: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.
解题代码如下:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode dummy{-1};
dummy.next = head;
ListNode *prev = &dummy, *cur = dummy;
for (int i = 0; cur && i != 2; ++i)
cur = cur -> next;
if (cur == 0) return head;
for (int i = 0; ; ++i) {
if (i % 2 == 0) {
prev -> next -> next= cur -> next;
cur -> next = prev -> next;
prev -> next = cur;
cur = cur -> next;
}
if (cur -> next == nullptr) break;
cur = cur -> next;
prev = prev -> next;
}
return dummy.next;
}
};
还有一个更简洁的代码(代码参考自网址https://github.com/soulmachine/leetcode#leetcode题解),但如下代码不符合题意要求(题意要求不允许修改结点的值)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* p = head;
while (p && p -> next) {
swap(p -> val, p -> next -> val);
p = p -> next -> next;
}
return head;
}
};