Leetcode 86. Partition List

Description: 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.

Link: https://leetcode.com/problems/partition-list/

Examples:

Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

思路: 用x把链表分成左右两部分,所以最简单的想法就是,遍历一遍链表,小于x的放在l1链表,大于等于x的放在l2链表,然后将l1,l2重新连接起来。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """
        if not head: return head
        if not head.next: return head
        
        l1 = ListNode(0) # left linked list head
        l2 = ListNode(0) # right linked list head
        pre = l1
        post = l2
        p = head
        while p:
            if p.val >= x:
                post.next = p
                post = post.next
            else:
                pre.next = p
                pre = pre.next
            p = p.next
        post.next = None
        pre.next = l2.next # link l1 and l2 into one linked list, heading l1
        return l1.next

日期: 2020-11-18 下雪了,雪地里一通乱踢,还把自己乐出了声

原文地址:https://www.cnblogs.com/wangyuxia/p/14002763.html