Partition List
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
.
思路: 分成两个链表,分别保存bigorgreater 和 less than
java代码:
- public ListNode partition(ListNode head, int x) {
- if(head == null) return null;
- ListNode small = null;
- ListNode smalltail = null;
- ListNode big = null;
- ListNode bigtail = null;
- ListNode p = head;
- while(p!=null) {
- if(p.val >= x) {
- if(big==null) {
- big = p;
- bigtail = p;
- } else {
- bigtail.next = p;
- bigtail = p;
- }
- } else {
- if(small==null) {
- small = p;
- smalltail = p;
- } else {
- smalltail.next = p;
- smalltail = p;
- }
- }
- p = p.next;
- }
- if(bigtail!=null) bigtail.next = null; //注意条件判断
- if(smalltail!=null) smalltail.next = big;
- if(small==null) return big;
- else return small;
- }
思路二:只用一条链表,把小的节点插入到前面,后面的保持不变
C++代码:
- ListNode *partition(ListNode *head, int x) {
- if(head == NULL) return NULL;
- ListNode *dummy = new ListNode(-1);
- dummy -> next = head;
- ListNode *p=head->next;
- ListNode *pre = head;
- ListNode *q=dummy;
- if(head->val < x) q=head;
- else q=dummy;
- while(p!=NULL) {
- if(p->val<x) {
- if(p==q->next) {
- pre=p;
- p=p->next;
- q=q->next;
- } else{
- pre->next=p->next;
- p->next=q->next;
- q->next=p;
- q=q->next;
- p=pre->next;
- }
- } else {
- pre=p;
- p=p->next;
- }
- }
- return dummy->next;
- }