两两交换链表中的节点
题目链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/
思路:三指针,考虑节点总数为奇数或偶数的情况。
参考代码:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) {
return head;
}
ListNode* pre = head;
ListNode* curr = head->next;
ListNode* temp = curr->next;
head = curr;
while (pre) {
curr->next = pre;
pre->next = temp;
if (!pre->next || !pre->next->next) {
break;
}
pre->next = pre->next->next;
pre = temp;
curr = pre->next;
temp = curr->next;
}
return head;
}
};