ParttiTion List 划分链表

本文介绍了一种链表划分算法,该算法将链表中小于给定值x的所有节点移至链表前部,同时保持相对顺序不变。通过双指针技巧实现,详细解释了其工作原理。

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

ParttiTion List 划分链表

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.

这道题要求我们划分链表,把所有小于给定值的节点都移到前面,大于该值的节点顺序不变,相当于一个局部排序的问题。

package leetcode;

/*
* 要求把小于x的元素按顺序放到链表前面。我们仍然是使用链表最常用的双指针大法,一个指向当前小于x的最后一个元素,
* 一个进行往前扫描。如果元素大于x,那么继续前进,否则,要把元素移到前面,并更新第一个指针。
* */

public class PartionList {
public ListNode partion (ListNode head ,int x){
if(head==null){
return null;
}
ListNode helper=new ListNode(0);
helper.next=head; //使用helper便于直接返回修改后的链表;
ListNode walker=helper;
ListNode runner=helper;
while(runner.next!=null){
if(runner.next.val

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值