每日一题
编写代码:以给定 x 为基准将链表分割成两部分,所有小于 x 的结点排在大于或等于 x 的结点之前。给定一个链表头指针,请返回重新排列后链表头指针。注意:分割以后保持原来数据顺序不变。
思路:
- 遍历整个链表,根据结点的值和 x 比较,分别插入到 < x 链表 或 大于等于 x 的链表中
- 直接把小于 和 大于等于的链表 连接起来
特殊性:
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();
}
}
结果