[LeetCode] Swap Nodes in Pairs 解题报告
来源:互联网 发布:东京食尸鬼口罩淘宝 编辑:程序博客网 时间:2024/06/06 03:52
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
Given
1->2->3->4
, you should return the list as 2->1->4->3
.Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
» Solve this problem
[解题思路]
双指针互换,要考虑一些边界条件,比如链表为空,链表长度为1,链表长度为2.
加一个safeGuard可以避开链表长度为2的检测。
[Code]
1: ListNode *swapPairs(ListNode *head) {
2: if(head == NULL) return NULL;
3: if(head->next == NULL) return head;
4: ListNode* safeG = new ListNode(-1);
5: safeG->next= head; // head will be changed in next switch
6: ListNode *pre = head->next;
7: ListNode *cur = head;
8: ListNode *post = safeG;
9: while(pre!=NULL)
10: {
11: ListNode* temp = pre->next;
12: pre->next = cur;
13: cur->next = temp;
14: post->next = pre;
15: post= cur;
16: if(post->next == NULL) break;
17: cur = post->next;
18: pre = cur->next;
19: }
20: head = safeG->next;
21: delete safeG;
22: return head;
23: }
Haoran给了一个递归解法,更简洁
1: ListNode *swapPairs(ListNode *head) {
2: if (head == NULL || head->next == NULL) {
3: return head;
4: }
5: ListNode* nextPair = head->next->next;
6: ListNode* newHead = head->next;
7: head->next->next = head;
8: head->next = swapPairs(nextPair);
9: return newHead;
10: }
0 0
- LeetCode解题报告--Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs 解题报告
- 【LeetCode】Swap Nodes in Pairs 解题报告
- Swap Nodes in Pairs LeetCode 解题报告
- 【LeetCode】Swap Nodes in Pairs 解题报告
- [leetcode] 24. Swap Nodes in Pairs 解题报告
- LeetCode 24. Swap Nodes in Pairs 解题报告
- [Leetcode] 24. Swap Nodes in Pairs 解题报告
- LeetCode 24. Swap Nodes in Pairs 解题报告
- leetcode解题报告24. Swap Nodes in Pairs
- [leetcode javascript解题]Swap Nodes in Pairs
- Leetcode #24. Swap Nodes in Pairs 链表节点交换 解题报告
- Swap Nodes in Pairs ——解题报告
- leetcode解题方案--024--Swap Nodes in Pairs
- LeetCode:Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [LeetCode] String to Integer (atoi) 解题报告
- [LeetCode] Subsets 解题报告
- [LeetCode] Subsets II 解题报告
- 提交Hadoop作业失败,报错Connection refused
- [LeetCode] Substring with Concatenation of All Words 解题报告
- [LeetCode] Swap Nodes in Pairs 解题报告
- [LeetCode] Symmetric Tree 解题报告
- [LeetCode] Text Justification 解题报告
- [LeetCode] Trapping Rain Water 解题报告
- android中的AIDL进程间通信
- [LeetCode] Triangle 解题报告
- [LeetCode] Unique Paths 解题报告
- [LeetCode] Unique Paths II 解题报告
- python生成随机数组