给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3 输出: 1->2->2->4->3->5
思路:用两个链表分别存小于x和大于等于x的元素,然后连接两个链表。在处理时,我开始只创建了一个新链表存放大于等于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): """ :type head: ListNode :type x: int :rtype: ListNode """ 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
#自己写的代码如下: # 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): """ :type head: ListNode :type x: int :rtype: ListNode """ 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