力扣0086——分隔链表

分隔链表

难度:中等

题目描述

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

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

示例1

origin_url=%2Fimages%2Fltc0086_1.jpg&pos_id=img-L6P08bQy-1706332388111)

复制代码
输入:head = [1,4,3,2,5,2], x = 3
输出:[1,2,2,4,3,5]

示例2

复制代码
输入:head = [2,1], x = 2
输出:[1,2]

题解

来用两个链表进行拼接,如果比目标值小就添加到第一个链表,比目标值大或与目标值相等就添加到第二个链表,最后将两个链表拼接

想法代码

csharp 复制代码
public class ListNode
{
    public int val;
    public ListNode next;

    public ListNode(int val = 0, ListNode next = null)
    {
        this.val = val;
        this.next = next;
    }
}

class Solution
{
    public static void Main(string[] args)
    {
        ListNode head = new ListNode(1)
        {
            next = new ListNode(4)
            {
                next = new ListNode(3)
                {
                    next = new ListNode(2)
                    {
                        next = new ListNode(5)
                        {
                            next = new ListNode(2)
                        }
                    }
                }
            }
        };
        Solution solution = new Solution();
        ListNode ans = solution.Partition(head, 2);
        while (ans != null)
        {
            Console.WriteLine(ans.val);
            ans = ans.next;
        }
    }

    public ListNode Partition(ListNode head, int x)
    {
        ListNode ans = head;
        ListNode temp1 = new ListNode();
        ListNode temp2 = new ListNode();
        ListNode s1 = temp1,s2 = temp2;
        while (ans != null)
        {
            if (ans.val < x)
            {
                s1.next = ans;
                s1 = s1.next;
            }
            else
            {
                s2.next = ans;
                s2 = s2.next;
            }
            ans = ans.next;
        }
        s1.next = temp2.next;
        s2.next = null;
        return temp1.next;
    }
}
相关推荐
05Kevin21 小时前
lk每日冒险题--数据结构6.27
算法
To_OC1 天前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安2 天前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
七牛开发者2 天前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent
kisshyshy2 天前
从递归到迭代,一文吃透二叉树的核心知识与 JavaScript 实现
javascript·算法·代码规范
To_OC2 天前
LC 49 字母异位词分组:想到哈希表很简单,选对 key 才是精髓
javascript·算法·leetcode
用户938515635073 天前
从 O(n²) 到 O(nlogn):一文读懂快速排序的“快”与“妙”
javascript·算法