Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
一个想法就是,首先找到一个节点,该节点的值小于x并且该节点的next节点的值大于等于x,这样的两个节点分别记为S和L,然后从L开始遍历链表,将小于x的值插入到S和L之间,并且更新S,L并不改变。这个想法值得注意的几点,第一个,head节点的值就大于x,则S为NULL,所有比x小的节点都要插入到Head之前,当插入第一个之后需要更新头节点,此后S不为NULL;第二个值得注意的就是每次插入SL之间后,需要更新S,否则出错。AC代码如下:
ListNode* partition(ListNode* head, int x) { if(!head) return head; //find two nodes ListNode * s=head; ListNode * l=NULL; if(head->val >= x) { l = head; s = NULL; } else { while(s->next!=NULL && s->next->val <x ) s=s->next; if(s->next == NULL) return head; l=s->next; } //search node less than x from node L ListNode *fir=l; ListNode *sec=fir->next; for(;sec!=NULL;) { if(fir->val>=x && sec->val < x) { fir->next = sec->next; if(s) { s->next = sec; sec->next = l; s= sec; } else { sec->next = l; head = sec; s= sec; } sec = fir->next; } else { fir = fir->next; sec = sec->next; } } return head; }
时间: 2024-09-29 10:42:54