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), *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;
}
还是递归版本清晰:
循环体的逻辑:主要变量:当前要交换的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; }
相关文章推荐
- 24. Swap Nodes in Pairs
- LeetCode 24 Swap Nodes in Pairs
- Swap Nodes in Pairs
- Leetcode——24. Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- 24. Swap Nodes in Pairs(第十七周)
- 24. Swap Nodes in Pairs
- 【LeetCode练习题】Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- LeetCode OJ:Swap Nodes in Pairs(成对交换节点)
- leetCode 24. Swap Nodes in Pairs 链表
- 【LeetCode】之Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs
- Leetcode -- swap nodes in pairs
- 24 Swap Nodes in Pairs
- 24.[Leetcode]Swap Nodes in Pairs
- LeetCode Swap Nodes in Pairs交换链表中的两个节点
- Swap Nodes in Pairs
- Swap Nodes in Pairs