[Leetcode][python]Partition List
来源:互联网 发布:自学编程先看什么书 编辑:程序博客网 时间:2024/06/01 07:33
题目大意
给定一个链表以及一个目标值,把小于该目标值的所有节点都移至链表的前端,大于或等于目标值的节点移至链表的尾端,同时要保持这两部分在原先链表中的相对位置。
解题思路
此题并不难,并且可以帮助理解链表。
两个指针,一个负责收集比目标小的,一个收集大于等于目标的。
代码
class Solution(object): def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ dummy = ListNode(-1) dummy.next = head small_dummy = ListNode(-1) large_dummy = ListNode(-1) # small_prev和large_prev往后遍历增加,small_dummy和large_dummy则负责最后作为返回头结点 small_prev = small_dummy large_prev = large_dummy while dummy.next: # head第一个节点 curr = dummy.next if curr.val < x: small_prev.next = curr small_prev = small_prev.next else: large_prev.next = curr large_prev = large_prev.next dummy = dummy.next large_prev.next = None # 最后指针置为none small_prev.next = large_dummy.next # large_dummy对应的是大链表的第一个数 return small_dummy.next # 返回的是small_dummy
总结
阅读全文
0 0
- partition List Leetcode Python
- [Leetcode][python]Partition List
- 【LeetCode with Python】 Partition List
- 【LEETCODE】86- Partition List [Python]
- LeetCode: Partition List
- LeetCode Partition List
- LeetCode: Partition List
- [Leetcode] Partition List **
- [Leetcode] Partition List
- [LeetCode] Partition List
- leetcode 81: Partition List
- [Leetcode] Partition List
- leetcode 118: Partition List
- [LeetCode]Partition List
- [leetcode]Partition List
- LeetCode-Partition List
- [leetcode] Partition List
- LeetCode - Partition List
- 最简单的方式用C表示摄氏温度和华氏温度的转换
- ubuntu16.04开启telnet服务
- org.springframework.web.filter.DelegatingFilterProxy
- 6. ZigZag Conversion
- Ubuntu 16.04设置root用户登录图形界面
- [Leetcode][python]Partition List
- Linux CentOS7下安装Zookeeper-3.4.10服务(最新)
- python @,@staticmethod,@classmethod
- Java泛型详解
- C++中的explicit关键字
- 190. Reverse Bits
- 从零基础认识maven工程构建
- java不同安装包的安装方法(rpm,bin,tar)
- 一元多项式的加法器 C语言版 链表版 顺序表版