分隔链表
1,程序简介
示例 1:
- 输入:head = [1,4,3,2,5,2], x = 3
- 输出:[1,2,2,4,3,5]
示例 2:
- 输入:head = [2,1], x = 2
- 输出:[1,2]
提示:
- 链表中节点的数目在范围 [0, 200] 内
- -100 <= Node.val <= 100
- -200 <= x <= 200
2,程序代码
"""
Created on Mon Jan 10 21:42:17 2022
Function: 分隔链表
@author: 小梁aixj
"""
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class LinkList:
def __init__(self):
self.head=None
def initList(self, data):
self.head = ListNode(data[0])
r=self.head
p = self.head
for i in data[1:]:
node = ListNode(i)
p.next = node
p = p.next
return r
def convert_list(self,head):
ret = []
if head == None:
return
node = head
while node != None:
ret.append(node.val)
node = node.next
return ret
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
if head is None:
return None
less = lesshead = None
last = pos = head
while pos is not None:
if pos.val < x:
if lesshead is None:
lesshead = pos
else:
less.next = pos
less = pos
if head == pos:
last = head = pos.next
else:
last.next = pos.next
else:
last = pos
pos = pos.next
if lesshead is not None:
less.next = head
else:
lesshead = head
return lesshead
l = LinkList()
list1 = [1,4,3,2,5,2]
l1 = l.initList(list1)
x = 3
s = Solution()
print(l.convert_list(s.partition(l1, x)))
3,运行结果
|