两两交换链表中的节点(leetcode24)c++
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
//1.分别遍历偶数节点和奇数节点
//2.交换两个节点
//3.更新pre,指向交换后的头
/**
* 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) {
//1.分别遍历偶数节点和奇数节点
//2.交换两个节点
//3.更新pre,指向交换后的头
//--[1]--
ListNode *new_head=new ListNode(0);
new_head->next=head;
ListNode *pre=new_head;
//~
//--[2]--
while(head && head->next){
//标记两个待交换结点
ListNode *first=head;
ListNode *second=head->next;
//swap
pre->next=second;
first->next=first->next->next;
second->next=first;
//更新pre
pre=first;
head=first->next;//后移
}
//~
//--[3]--
return new_head->next;
//~
}
};