题目链接:
题目描述:
将一个链表重排,比x小的节点在大于或等于x的节点前面。不改变之前的相对顺序,只是把比x小的节点,按之前相对先后顺序,放在前面。
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
分析:
一些小问题还是调了有好久。加了一个头指针的节点pHead,方便在head之前插入节点。
代码:
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* pHead=(ListNode*)malloc(sizeof(ListNode));
pHead->next=head;
ListNode* less=pHead;
ListNode* pre=pHead;
ListNode* cur=head;
while(cur!=NULL){
if(cur->val<x){
if(pre==less){ //当pre与less保持同步时,表明还没有发现比x大的节点
less=cur;
pre=cur;
cur=cur->next;
}
else{
ListNode* tmpLess=less->next;
pre->next=cur->next;
less->next=cur;
cur->next=tmpLess;
less=cur;
cur=pre->next;
}
}
else{
pre=cur;
cur=cur->next;
}
}
return pHead->next;
}
};