LeetCode题解:Swap Nodes in Pairs
2013-11-08 09:56
465 查看
Swap Nodes in Pairs
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.
思路:
一般来说是交换相邻的两个结点的内容就可以解决,无奈题目不允许这么做。只能交换指针了。要注意的是,指向每一对结点中前一个结点的指针也必须更改。
题解:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *swapPairs(ListNode *head) { if (!head) return nullptr; ListNode* nh = new ListNode(0); nh->next = head; ListNode* h0 = nh; ListNode* h1 = head; ListNode* h2 = head->next; while(h2 != nullptr) { h1->next = h2->next; h2->next = h1; h0->next = h2; h0 = h1; h1 = h1->next; h2 = (h1 ? h1->next : nullptr); } h0 = nh->next; delete nh; return h0; } };
相关文章推荐
- [LeetCode]题解(python):024-Swap Nodes in Pairs
- leetcode题解-24. Swap Nodes in Pairs
- Leetcode题解-24. Swap Nodes in Pairs
- leetcode题解-24. 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题解 24. Swap Nodes in Pairs
- LeetCode24之SwapNodesInPairs的Java 题解
- 25 leetcode - Swap Nodes in Pairs
- [leetcode]24. Swap Nodes in Pairs(java)
- 【leetcode】24. Swap Nodes in Pairs - 成对交换链表元素
- LeetCode | Swap Nodes in Pairs(将链表中的元素两两交换)
- [LeetCode]Swap Nodes in Pairs
- [C语言][LeetCode][24]Swap Nodes in Pairs
- 【leetcode】swap-nodes-in-pairs
- LeetCode 24 Swap Nodes in Pairs(交换序列中的结点)(Linked List)
- Leetcode: Swap Nodes in Pairs
- leetcode: Swap Nodes in Pairs (C++)