leetcode24. Swap Nodes in Pairs
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
int step = 2;
ListNode *front = new ListNode(0);
front->next = head;
ListNode *tail = front;
ListNode *lHead = front;
if(head==NULL){
return NULL;
}
if(head->next==NULL){
return head;
}
while(tail->next!=NULL){
tail = tail->next;
if(step<=1){
front->next->next = tail->next;
tail->next = front->next;
front->next = tail;
tail = tail->next;
front = tail;
step = 2;
}else{
step--;
}
}
return lHead->next;
}
};
本文提供了一个简洁且高效的C++解决方案,用于解决LeetCode第24题“两两交换链表中的节点”。通过迭代方式实现节点的交换,避免了递归可能带来的堆栈溢出问题。文章中的代码清晰地展示了如何通过引入虚拟头节点简化边界条件处理。
527

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



