2023每日刷题(八十七)
Leetcode—24. 两两交换链表中的节点
实现代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode(0, head);
ListNode* tmp = head;
int n = 0;
while(tmp) {
n++;
tmp = tmp->next;
}
if(n == 0 || n == 1) {
return head;
}
ListNode* p0 = dummy, *pre = nullptr;
ListNode* cur = head;
for(; n >= 2; n -= 2) {
for(int i = 0; i < 2; i++) {
ListNode* nxt = cur->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
ListNode* nxxt = p0->next;
p0->next->next = cur;
p0->next = pre;
p0 = nxxt;
}
return dummy->next;
}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!