题目描述
编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
import java.util.*;
/**
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Partition {
public ListNode partition(ListNode pHead, int x) {
if(pHead==null) return null;
ListNode beforeStart=null;
ListNode beforeEnd=null;
ListNode afterStart=null;
ListNode afterEnd=null;
ListNode temp=pHead;
while(temp!=null){
ListNode next=temp.next;
temp.next=null;
if(temp.val<x){
if(beforeStart==null){
beforeStart=temp;
beforeEnd=temp;
}else{
beforeEnd.next=temp;
beforeEnd=temp;
}
}else{
if(afterStart==null){
afterStart=temp;
afterEnd=temp;
}else{
afterEnd.next=temp;
afterEnd=temp;
}
}
temp=next;
}
if(beforeStart==null){
return afterStart;
}else{
beforeEnd.next=afterStart;
return beforeStart;
}
}
}
本文介绍了一种链表分割算法,该算法能够根据给定值x将链表分割成两部分,使得所有小于x的结点排在大于或等于x的结点前面,同时保持原有的数据顺序不变。
277

被折叠的 条评论
为什么被折叠?



