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;
}
};
相關文章
- 024,Swap Nodes in PairsAI
- Leetcode 24 Swap Nodes in PairsLeetCodeAI
- 【leetcode】24. Swap Nodes in Pairs 連結串列奇偶節點交換LeetCodeAI
- 兩種解法搞定Swap Nodes in Pairs演算法題AI演算法
- The best LeetCode NodesLeetCode
- 13-Architecture-nodes
- TWO NODES(HDU-4587)
- [LeetCode] 336. Palindrome PairsLeetCodeAI
- 1512. Number of Good PairsGoAI
- 【Lintcode】572. Music PairsAI
- CF1762F Good PairsGoAI
- Leetcode 25 Reverse Nodes in k-GroupLeetCode
- 24.【水仙花數】
- [LeetCode] 2487. Remove Nodes From Linked ListLeetCodeREM
- 【Leetcode】25.Reverse Nodes in k-GroupLeetCode
- swap 跟 fstab
- swap擴容
- Vim auto-pairs設定選項AI
- CF Div. 3 C Beautiful Triple PairsAI
- [LeetCode] 1497. Check If Array Pairs Are Divisible by kLeetCodeAI
- [Leetcode力扣 25] Reverse Nodes in k-GroupLeetCode力扣
- IPP SWAP孵化器|IPP SWAP系統開發分析
- 24. 使用MySQL之使用遊標MySql
- E - Remove Pairs(狀壓dp+博弈論)REMAI
- Diff-prime Pairs(思維+素數篩)AI
- Solution - Atcoder ABC263G Erasing Prime PairsAI
- [LeetCode] 3184. Count Pairs That Form a Complete Day ILeetCodeAIORM
- Linux Swap擴容Linux
- 【LeetCode】493. Reverse Pairs 翻轉對(Hard)(JAVA)LeetCodeAIJava
- 222. Count Complete Tree Nodes(Leetcode每日一題-2020.11.24)LeetCode每日一題
- LINUX 建立swap空間Linux
- linux 修改swap空間Linux
- linux 禁止swap交換Linux
- 劍指 Offer 24. 反轉連結串列
- 劍指 Offer 24.反轉連結串列
- oracle RAC dbca的時候報錯提示cluster nodes are not accessibleOracle
- Waring: /dev/centos/swap does not existdevCentOS
- CAS 演算法 —— Compare and Swap演算法
- IPP SWAP的創新模式模式