【Leetcode】【python】Swap Nodes in Pairs
来源:互联网 发布:淘宝联盟手机版如何用 编辑:程序博客网 时间:2024/06/11 18:10
题目大意
交换链表中相邻的两个元素。
注意第一个节点与第二个节点要交换位置,而第二个节点不用与第三个节点交换位置。
注意点:
不允许修改节点的值
只能用常量的额外空间
解题思路
该题费脑,绕来绕去的指向,这个解读比较清晰
来自:
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
总结
阅读全文
0 0
- 【LeetCode with Python】 Swap Nodes in Pairs
- Swap Nodes in Pairs Leetcode Python
- 24. Swap Nodes in Pairs Leetcode Python
- [leetcode: Python]24. Swap Nodes in Pairs
- 【Leetcode】【python】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] 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 - Swap Nodes in Pairs
- LeetCode | Swap Nodes in Pairs
- 【leetcode】Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- Busybox 命令大全~~
- 关于Java的File.separator
- Python 读文件代码示例
- C++ 读文件示例代码
- Ubuntu下中文输入法的解决办法
- 【Leetcode】【python】Swap Nodes in Pairs
- Spring-AOP @AspectJ切点函数之@within()和@target
- C#--继承的关键字
- Python之 __slots__ 的用法
- Android底部菜单-FragmentTabHost实现
- nohup介绍
- ZeroBrane Studio 设置
- 【LeetCode】Partition List 链表划分
- Python之 @property 用法