static int dividend=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
/**
* 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) {
if (head == NULL)
return NULL;
if (head->next == NULL)
return head;
ListNode* prv = head;
ListNode* mid = head;
ListNode* last = head->next;
while(1){
if (prv != mid){
prv->next = mid->next;
mid->next = last->next;
last->next = mid;
}else{
mid->next = last->next;
last->next = mid;
head = last;
}
if (mid->next == NULL || mid ->next->next == NULL)
return head;
else{
prv = mid;
last = mid->next->next;
mid = mid->next;
}
}
}
};
LetCode 24. 两两交换链表中的节点
最新推荐文章于 2025-04-29 15:28:59 发布
本文介绍了一个C++实现的算法,该算法用于交换给定链表中的节点对。通过迭代方式遍历链表并调整相邻节点的连接顺序来完成节点对的交换。此算法适用于两两相邻节点的顺序反转。
1165

被折叠的 条评论
为什么被折叠?



