LeetCode:86. 分隔链表(python3)
Posted 南岸青栀*
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:86. 分隔链表(python3)相关的知识,希望对你有一定的参考价值。
86. 分隔链表
法1:暴力求解
将数据存储在两个数组中,然后合并两个数据。重新构建数组。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
lst1 = []
lst2 = []
p = head
while p:
if p.val < x:
lst1.append(p.val)
else:
lst2.append(p.val)
p = p.next
lst1.extend(lst2)
cur = ListNode(-1)
res = cur
for i in lst1:
cur.next = ListNode(i)
cur = cur.next
return res.next
优化一下:
思路差不多吧,不过是直接创建两个链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
lh = left = ListNode(-1)
rh = right = ListNode(-1)
while head:
if head.val < x:
left.next = ListNode(head.val)
left = left.next
else:
right.next = ListNode(head.val)
right = right.next
head = head.next
left.next = rh.next
return lh.next
法2:四指针解法(改动原链表)
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
cur = ListNode(-1)
cur.next = head
p_pre,p = cur,cur.next
#寻找出第一个大于等于x的节点
while p and p.val < x:
p = p.next
p_pre = p_pre.next
#如果p==None,说明链表已经排列好了
if p == None : return head
l,l_pre = p.next,p
#在第一个大于等于x的节点后的小于x的节点都移动到p_pre,p之间
while l:
#如果大于等于x则不需要移动
if l.val >= x:
l = l.next
l_pre = l_pre.next
else:
#将该节点移动到,p_pre,p之间
l_pre.next = l.next
p_pre.next = l
l.next = p
#变更p_pre和l
p_pre = l
l = l_pre.next
return cur.next
以上是关于LeetCode:86. 分隔链表(python3)的主要内容,如果未能解决你的问题,请参考以下文章