LeetCode --- 24. Swap Nodes in Pairs
2015-02-01 16:56
267 查看
题目链接: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.
这道题的要求是交换链表中相邻的节点。要求:使用恒定空间,不允许修改链表中的数值,仅可以改变链表节点本身。
这道题考察的是链表处理,同样还是现在链表前面加个头,便于统一处理链表的所有节点。
时间复杂度:O(n)
空间复杂度:O(1)
转载请说明出处:LeetCode --- 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.
这道题的要求是交换链表中相邻的节点。要求:使用恒定空间,不允许修改链表中的数值,仅可以改变链表节点本身。
这道题考察的是链表处理,同样还是现在链表前面加个头,便于统一处理链表的所有节点。
[code]假设链表为: head -> 1 -> 2 -> 3 -> 4 -> NULL。 加头之后为: h -> 0 -> 1 -> 2 -> 3 -> 4 -> NULL。 可先领p指向要交换节点的第一个节点的前一节点,temp指向要交换节点的第一个节点,即: h -> 0 -> 1 -> 2 -> 3 -> 4 -> NULL ^ ^ | | p temp 接下来,要使1和2两个节点交换,只需要交换其指针指向即可,即先将p->next指向节点2: |-------->| h -> 0 1 -> 2 -> 3 -> 4 -> NULL ^ ^ | | p temp 然后temp->next指向节点3: |-------->| h -> 0 1 2 -> 3 -> 4 -> NULL ^ |-------->| | ^ p | temp 最后再使节点2的next指回节点1: |-------->| h -> 0 1 <- 2 3 -> 4 -> NULL ^ |-------->| | ^ p | temp 即: h -> 0 -> 2 -> 1 -> 3 -> 4 -> NULL ^ ^ | | p temp 接下来再移动p指针到下一要交换节点对的前面(即temp处)即可: h -> 0 -> 2 -> 1 -> 3 -> 4 -> NULL ^ | p 进而继续交换节点3和节点4,以此类推,进行循环。。。
时间复杂度:O(n)
空间复杂度:O(1)
[code] 1 class Solution 2 { 3 public: 4 ListNode *swapPairs(ListNode *head) 5 { 6 ListNode *h = new ListNode(0), *p = h; 7 h -> next = head; 8 9 while(p -> next != NULL && p -> next -> next != NULL) 10 { 11 ListNode *temp = p -> next; 12 p -> next = temp -> next; 13 temp -> next = p -> next -> next; 14 p -> next -> next = temp; 15 p = temp; 16 } 17 18 return h -> next; 19 } 20 };
转载请说明出处:LeetCode --- 24. Swap Nodes in Pairs
相关文章推荐
- 【leetcode】24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs Leetcode Python
- [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 24. Swap Nodes in Pairs
- 【leetcode】24. Swap Nodes in Pairs
- leetcode_24. Swap Nodes in Pairs C++
- leetcode 24. Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- LeetCode24. 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
- (Java)LeetCode-24. Swap Nodes in Pairs