LeetCode----Partition List
2015-11-01 16:29
591 查看
Partition List
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given
return
分析:
实现链表的分割,类似于快排中的分割。
我的方法非常简单,遍历链表,建立两个链表,s表示小链表,里面的元素值均小于给定元素x;b表示大链表,里面的元素均大于等于给定元素x。
遍历时,对每个节点进行判断,然后放入对应的s或b的链表,最后再将s和b链表进行连接返回。
代码:
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
p = head
ss = s = ListNode(-1) # ss record the start of smaller linkedlist, s record the node in smaller linkedlist
sb = b = ListNode(-1) # sb record the start of bigger linkedlist, b record the node in bigger linkedlist
while p:
if p.val >= x:
b.next = p
p = p.next
b = b.next
b.next = None
else:
s.next = p
p = p.next
s = s.next
s.next = None
s.next = sb.next
return ss.next
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given
1->4->3->2->5->2and x = 3,
return
1->2->2->4->3->5.
分析:
实现链表的分割,类似于快排中的分割。
我的方法非常简单,遍历链表,建立两个链表,s表示小链表,里面的元素值均小于给定元素x;b表示大链表,里面的元素均大于等于给定元素x。
遍历时,对每个节点进行判断,然后放入对应的s或b的链表,最后再将s和b链表进行连接返回。
代码:
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
p = head
ss = s = ListNode(-1) # ss record the start of smaller linkedlist, s record the node in smaller linkedlist
sb = b = ListNode(-1) # sb record the start of bigger linkedlist, b record the node in bigger linkedlist
while p:
if p.val >= x:
b.next = p
p = p.next
b = b.next
b.next = None
else:
s.next = p
p = p.next
s = s.next
s.next = None
s.next = sb.next
return ss.next
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- [C/C++]反转链表
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例