86.分割链表
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3 输出: 1->2->2->4->3->5
思路:用两个链表分别存小于x和大于等于x的元素,然后连接两个链表。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
f, b = ListNode(-1), ListNode(-1)
f1, b1 = f, b
while head:
if head.val < x:
f1.next, head = head, head.next
f1 = f1.next
f1.next = None
else:
b1.next, head = head, head.next
b1 = b1.next
b1.next = None
f1.next = b.next
return f.next
#自己写的代码如下:
class Solution(object):
def partition(self, head, x):
dummynode = ListNode(None)
dummynode.next = None
pre = dummynode
p = head
cur = p
while cur!=None:
if cur.val<x:
if p == cur:
cur = cur.next
else:
p.next = cur
p = cur
cur = cur.next
else:
pre.next = cur
pre = cur
cur = cur.next
pre.next = None
if dummynode.next != None:
p.next = dummynode.next
return head