【Leetcode】【python】Swap Nodes in Pairs
2017-09-05 06:03
507 查看
题目大意
交换链表中相邻的两个元素。注意第一个节点与第二个节点要交换位置,而第二个节点不用与第三个节点交换位置。
注意点:
不允许修改节点的值
只能用常量的额外空间
解题思路
该题费脑,绕来绕去的指向,这个解读比较清晰来自:
https://shenjie1993.gitbooks.io/leetcode-python/024%20Swap%20Nodes%20in%20Pairs.html
比较常见的链表操作。下面看一下典型情况,如要交换链表中A->B->C->D中的B和C需要做如下操作:
将A指向C
将B指向D
将C指向B
在头节点之前加一个假节点就可以使所有的交换都符合上面的情况。
代码
class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ prev = ListNode(-1) prev.next = head temp = prev while temp.next and temp.next.next: node1 = temp.next # A node2 = temp.next.next # B temp.next = node2 # A->C node1.next = node2.next # B->D node2.next = node1 # C->B? temp = temp.next.next # 跳过两个 return prev.next
总结
相关文章推荐
- Leetcode_swap-nodes-in-pairs(c++ and python version)
- [LeetCode]题解(python):024-Swap Nodes in Pairs
- Swap Nodes in Pairs Leetcode Python
- leetcode 【 Linked List Swap Nodes in Pairs 】 python 实现
- python实现 LeetCode24——Swap Nodes in Pairs
- 【LeetCode with Python】 Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs (Python)
- [leetcode]Swap Nodes in Pairs @ Python
- leetcode 【 Swap Nodes in Pairs 】python 实现
- 24. Swap Nodes in Pairs Leetcode Python
- leetcode Swap Nodes in Pairs python
- python写算法题:leetcode: 24. Swap Nodes in Pairs
- LeetCode 24 Swap Nodes in Pairs (C,C++,Java,Python)
- [leetcode: Python]24. Swap Nodes in Pairs
- [leetcode]Swap Nodes in Pairs @ Python
- LeetCode解题报告--Swap Nodes in Pairs
- [leetcode 26] Swap Nodes in Pairs
- LeetCode刷题——Swap Nodes in Pairs(Medium)
- Leetcode 之 Swap Nodes in Pairs
- LeetCode解题报告—— Swap Nodes in Pairs & Divide Two Integers & Next Permutation