leetcode: 24. Swap Nodes in Pairs
来源:互联网 发布:淘宝评论显示有违禁词 编辑:程序博客网 时间:2024/06/18 17:24
Problem
# 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.
AC
class ListNode(): def __init__(self, x): self.val = x self.next = Noneclass Solution(): def swapPairs(self, x): cur = dummy = ListNode(0) tmp, step = None, 1 while x: if step % 2: tmp = ListNode(x.val) else: cur.next, cur.next.next = ListNode(x.val), tmp cur, tmp = cur.next.next, None x, step = x.next, step + 1 if tmp: cur.next = tmp return dummy.nextif __name__ == "__main__": x, x.next, x.next.next, x.next.next.next = ListNode(1), ListNode(2), ListNode(3), ListNode(4) res = Solution().swapPairs(x) assert '{0}->{1}->{2}->{3}'.format(res.val, res.next.val, res.next.next.val, res.next.next.next.val) \ == '2->1->4->3'
阅读全文
2 0
- [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
- 24. Swap Nodes in Pairs LeetCode
- 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
- LeetCode 24. Swap Nodes in Pairs
- 欢迎使用CSDN-markdown编辑器
- 我理解的计算机
- C语言02
- IoC 容器和 Dependency Injection 模式
- 汇总linux下安装软件的几种方式------写的很好
- leetcode: 24. Swap Nodes in Pairs
- C和指针之函数之求最大公约数
- PAT (Basic Level) Practise (中文)1031. 查验身份证(15)
- 1145 求图像的周长
- 救济金发放
- java数据结构与算法--第一章总结
- 微信定时向好友发信息(循环发信息)
- <context:annotation-config> 和 <context:component-scan>的区别
- jQuery教程