您的位置:首页 > Web前端 > Node.js

Swap Nodes in Pairs

2014-08-18 14:28 239 查看
主框架就是遍历,循环条件是p && p->next,保证有2个node.

循环体的逻辑:主要变量:当前要交换的node, p, p->next, 左边连接的节点prev, 右边连接的节点,要做的事就是交换两个节点,并且处理好左边和右边与外部链表的连接。

ListNode *swapPairs(ListNode *head) {
ListNode dummy(-1);
dummy.next=head;
ListNode *prev=&dummy, *p=head;

while(p && p->next)
{
ListNode* second= p->next; //keep the right outer node
p->next=second->next; //connect the 1st node to the right outer node
second->next=p; //connect the 2nd node to the 1st node
prev->next=second; // connect the left outer node to the 2nd node
prev=p; //update left outer node
p=p->next;// update the current pointer
}
return dummy.next;
}


用合适的变量名,使得指针清晰

ListNode *swapPairs(ListNode *head) {
ListNode dummy(-1), *prev = &dummy;
dummy.next = head;
for (ListNode *second, *third; head && head->next; prev = head, head = third) {
second = head->next, third = second->next;
second->next = head;
head->next = third;
prev->next = second;
}
return dummy.next;
}

还是递归版本清晰:

ListNode *swapPairs(ListNode *head) {
if (!head || !head->next) return head;
auto second = head->next, third = second->next;
second->next = head;
head->next = swapPairs(third);
return second;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: