public class Partition {
public ListNode partition(ListNode pHead, int x) {
// write code here
//把总的链表拆成连个独立的链表
ListNode lowHead = null,highHead =null,curLow = null,curHigh=null,cur;
while(pHead!=null){
cur = pHead;
pHead = pHead.next;
cur.next = null;
if(cur.val < x){
if(lowHead == null)
lowHead = cur;
else
curLow .next = cur;
curLow = cur;
}else{
if(highHead == null)
highHead = cur;
else
curHigh .next = cur;
curHigh = cur;
}
}
//链接两个链表
if(curLow !=null)
curLow.next = highHead;
return curLow == null? highHead:lowHead;
}
}
题目描述
public class Partition {
public ListNode partition(ListNode pHead, int x) {
// write code here
//把总的链表拆成连个独立的链表
ListNode lowHead = null,highHead =null,curLow = null,curHigh=null,cur;
while(pHead!=null){
cur = pHead;
pHead = pHead.next;
cur.next = null;
if(cur.val < x){
if(lowHead == null)
lowHead = cur;
else
curLow .next = cur;
curLow = cur;
}else{
if(highHead == null)
highHead = cur;
else
curHigh .next = cur;
curHigh = cur;
}
}
//链接两个链表
if(curLow !=null)
curLow.next = highHead;
return curLow == null? highHead:lowHead;
}
}
编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。