以给定值为基准将链表分割

每日一题
编写代码:以给定 x 为基准将链表分割成两部分,所有小于 x 的结点排在大于或等于 x 的结点之前。给定一个链表头指针,请返回重新排列后链表头指针。注意:分割以后保持原来数据顺序不变

思路:

  1. 遍历整个链表,根据结点的值和 x 比较,分别插入到 < x 链表 或 大于等于 x 的链表中
  2. 直接把小于 和 大于等于的链表 连接起来
      特殊性:
            1. 整个链表是空的
            2. 没有小于x 的
            3. 没有大于等于 x 的

代码

class ListNode{
 int val;
 ListNode next;
 ListNode(int x){
  val=x;
 }
}
class Solution{
//以给定值x为基准,将链表分两部分
 public ListNode partition(ListNode pHead,int x){
  //small 是小于 x 的链表
  //big 是大于等于 x 的链表
  ListNode small=null;
  ListNode big=null;
  ListNode smallLast=null;
  ListNode bigLast=null;
  for(ListNode cur=pHead;cur!=null;cur=cur.next){
   if(cur.val<x){
    if(small==null){
     small=cur;
    }else{
     smallLast.next=cur;
    }
    smallLast=cur;
   }else{
    if(big==null){
     big=cur;
    }else{
     bigLast.next=cur;
    }
    bigLast=cur;
   }
  }
  //容易忘的点:需保证链表最后一个结点 next == null
  if(small==null){
   return big;
  }else{
   smallLast.next=big;
   bigLast.next=null;
   return small;
  }
 }
} 
public class Situation{
 public static void display(ListNode head){
  for(ListNode n=head;n!=null;n=n.next){
   System.out.printf("(%d)-->",n.val);
  }
  System.out.println("null");
 }
 public static void testPartition(){
  System.out.println("测试以 x 为 基准排序");
   
  ListNode n1=new ListNode(7);
  ListNode n2=new ListNode(2);
  ListNode n3=new ListNode(1);
  ListNode n4=new ListNode(4);
  ListNode n5=new ListNode(6);
  n1.next=n2;
  n2.next=n3;
  n3.next=n4;
  n4.next=n5;
  n5.next=null;
   
  Solution s=new Solution();
  ListNode result=s.partition(n1,3);
   //打印result
   display(result); 
 }
 public static void main(String[] args){
 testPartition();
 }
}


结果
在这里插入图片描述

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值