题目
现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。
题目解析:
思路:
代码:
public class Partition {
public ListNode partition(ListNode pHead, int x) {
// write code here
if(pHead == null){
return null;
}
if(pHead.next == null){
return pHead;
}
ListNode smallHead = new ListNode(0);
ListNode smallTail = smallHead;
ListNode bigHead = new ListNode(0);
ListNode bigTail = bigHead;
for(ListNode cur = pHead; cur != null;cur = cur.next){
if(cur.val < x){
smallTail.next = new ListNode(cur.val);
smallTail = smallTail.next;
}else{
bigTail.next = new ListNode(cur.val);
bigTail = bigTail.next;
}
}
smallTail.next = bigHead.next;//bigTail有傀儡节点,所以要跳到next
return smallHead.next;
}
}