Leetcode86. 分隔链表(golang)

一、题目

题目来源:https://leetcode-cn.com/problems/partition-list/

给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

  • 示例 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

二、题解

利用双指针求解:

  • 这里我们可以创建两个新的链表,smallh用来存放小于x的结点,largeh用来存放大于x的结点。
  • 同时设置smalllarge指针用来移动并在新链表中添加判断过大小的结点。
  • 最后当head遍历完链表之后,将small指针连接至largeh.Next,拼接成完整的链表,返回smallh.Next

图示如下:

在这里插入图片描述

  • 时间复杂度为:
    0 ( n ) 0(n) 0(n)
  • 空间复杂度为:
    0 ( 1 ) 0(1) 0(1)

代码

func partition(head *ListNode, x int) *ListNode {
    
    
    small := &ListNode{
    
    }
    large := &ListNode{
    
    }
    smallh := small
    largeh := large
    for head != nil {
    
    
        if head.Val < x {
    
    
            small.Next = head
            small = small.Next
        } else {
    
    
            large.Next = head
            large = large.Next
        }
        head = head.Next
    }
    large.Next = nil
    small.Next = largeh.Next
    return smallh.Next
}

猜你喜欢

转载自blog.csdn.net/QQ395879676/article/details/115550301