思路
首先给原单链表加上一个无意义的头结点,可以统一单链表为空时的处理。
两两结点进行交换,用头结点做辅助,即三个结点看做一组。
处理过程是三个步骤,首先将cur指针指向head。
初始状态为:
第一步,将1指向3。这会丢失2结点,因此需要用temp结点暂存2。
第二步,将2指回1。
第三步,将cur指向2。
最后,使用cur进行遍历
代码
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* newhead = new ListNode(0, head); // 新头结点
ListNode* cur = newhead;
while (cur->next != nullptr && cur->next->next != nullptr) {
ListNode* temp = cur->next->next; // 暂存“2号”结点
// 上述三个步骤
cur->next->next = temp->next;
temp->next = cur->next;
cur->next = temp;
cur = cur->next->next;
}
return newhead->next;
}
};