24. Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example,
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.
解法一:遞迴
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* new_head = head->next;
head->next = swapPairs(new_head->next);
new_head->next = head;
return new_head;
}
};
解法二:非遞迴
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* new_head = NULL;
ListNode** pp = &new_head;
while(head != NULL){
if(head->next == NULL){
*pp = head;
break;
}
else{
*pp = head->next;
head->next = (*pp)->next;
(*pp)->next = head;
pp = &(head->next);
head = head->next;
}
}
return new_head;
}
};
相關文章
- Swap Nodes in PairsAI
- 024,Swap Nodes in PairsAI
- 【leetcode】24. Swap Nodes in Pairs 連結串列奇偶節點交換LeetCodeAI
- Leetcode Swap Nodes in PairsLeetCodeAI
- Leetcode 24 Swap Nodes in PairsLeetCodeAI
- LeetCode 24 Swap Nodes in PairsLeetCodeAI
- Leetcode-Swap Nodes in PairsLeetCodeAI
- Swap Nodes in Pairs leetcode javaAILeetCodeJava
- Leetcode 線性表 Swap Nodes in PairsLeetCodeAI
- [LeetCode] Swap Nodes in Pairs 成對交換節點LeetCodeAI
- 兩種解法搞定Swap Nodes in Pairs演算法題AI演算法
- 【LeetCode】Swap Nodes in Pairs 連結串列指標的應用LeetCodeAI指標
- Palindrome PairsAI
- 11.2.0.1 rac 2nodes asm aix6.1 orarootagent.bin swap memory記憶體洩漏ASMAI記憶體
- 11.2.0.1 rac 2nodes asm aix6.1 orarootagent.bin swap memory記憶體洩漏ASMAI記憶體
- 13-Architecture-nodes
- 【Lintcode】572. Music PairsAI
- 1512. Number of Good PairsGoAI
- LeetCode-Palindrome PairsLeetCodeAI
- 532. K-diff Pairs in an ArrayAI
- Bootstrap系列 -- 24. 下拉選單基本用法boot
- HINT no_swap_join_inputs/swap_join_inputs
- Vim auto-pairs設定選項AI
- 【LeetCode】Palindrome Pairs(336)LeetCodeAI
- [LeetCode] 336. Palindrome PairsLeetCodeAI
- Diff-prime Pairs(思維+素數篩)AI
- LeetCode677. Map Sum PairsLeetCodeAI
- LeetCode-Find K Pairs with Smallest SumsLeetCodeAI
- IPP SWAP孵化器|IPP SWAP系統開發分析
- Leetcode Reverse Nodes in k-GroupLeetCode
- One cause leads to the error(The specified nodes are not clusterable)Error
- OCR integrity results are inconsistent amongst the nodes.
- get_swap.sh
- MySQL之swap配置MySql
- Linux新增SWAPLinux
- linux swap(交換)Linux
- Lua中ipairs()和pairs()的區別與使用AI
- 24. 平衡二叉樹,及其程式碼實現二叉樹