力扣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;
    }
}
相关推荐
姚先生971 小时前
LeetCode 贪心算法经典题目 (C++实现)
c++·leetcode·贪心算法
CodeJourney.1 小时前
DeepSeek在MATLAB上的部署与应用
数据库·人工智能·算法·架构
苦学编程的谢2 小时前
链表(LinkedList)面试题
数据结构·链表
烟雨迷2 小时前
八大排序算法(C语言实现)
c语言·数据结构·学习·算法·排序算法
emmmmXxxy2 小时前
leetcode刷题-动态规划08
算法·leetcode·动态规划
tt5555555555552 小时前
每日一题——打家劫舍
c语言·数据结构·算法·leetcode
xing.yu.CTF3 小时前
Alice与Bob-素数分解密码学
算法·密码学
瓦力的狗腿子3 小时前
Starlink卫星动力学系统仿真建模第十讲-基于SMC和四元数的卫星姿态控制示例及Python实现
开发语言·python·算法
闻缺陷则喜何志丹3 小时前
【二分查找】P11201 [JOIG 2024] たくさんの数字 / Many Digits|普及
c++·算法·二分查找·洛谷·字符·数字·需要
shinelord明4 小时前
【再谈设计模式】访问者模式~操作对象结构的新视角
开发语言·数据结构·算法·设计模式·软件工程