[LeetCode][Java] Partition List

本文详细介绍了如何使用链表和目标值x对链表进行分割,使得所有小于x的节点位于前面,且保留原始相对顺序。通过两次遍历实现,最终合并两个分割部分得到结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

题意:

给定一个链表和一个值x,分割链表使得比x小的节点都在大于或等于x的节点的前面。

你需要分别在这两个分割的部分中保持节点原始的相对顺序。

比如,

给定1->4->3->2->5->2 和 x =3 ,

返回1->2->2->4->3->5.

算法分析:

  * 分两次遍历单链表

  * 一次记录比目标值小的所有值

  * 一次记录比目标值大的所有值

  * 最终将这两个记录合并

  * 得到最终的结果

AC代码:

<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution 
{
    public ListNode partition(ListNode head, int x) 
    {
    	if(head==null) return head;
    	ListNode fhead = head;
    	ListNode shead = head;
    	ListNode res=new ListNode(0) ;
    	ListNode fres=res;
    	while(fhead!=null)
    	{
    		if(fhead.val<x)
    		{
    			res.next= new ListNode(fhead.val);
    			res=res.next;
    		}
    		fhead=fhead.next;
    	}
    	while(shead!=null)
    	{
    		if(shead.val>=x)
    		{
    			res.next= new ListNode(shead.val);
    			res=res.next;
    		}
			shead=shead.next;
    	}
    	return fres.next;
    }
}</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值