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代码:

  1. public ListNode partition(ListNode head, int x) {
  2. if(head == null) return null;
  3. ListNode small = null;
  4. ListNode smalltail = null;
  5. ListNode big = null;
  6. ListNode bigtail = null;
  7. ListNode p = head;
  8. while(p!=null) {
  9. if(p.val >= x) {
  10. if(big==null) {
  11. big = p;
  12. bigtail = p;
  13. } else {
  14. bigtail.next = p;
  15. bigtail = p;
  16. }
  17. } else {
  18. if(small==null) {
  19. small = p;
  20. smalltail = p;
  21. } else {
  22. smalltail.next = p;
  23. smalltail = p;
  24. }
  25. }
  26. p = p.next;
  27. }
  28. if(bigtail!=null) bigtail.next = null;  //注意条件判断
  29. if(smalltail!=null) smalltail.next = big;
  30. if(small==null) return big;
  31. else return small;
  32. }

思路二:只用一条链表,把小的节点插入到前面,后面的保持不变

C++代码:

  1. ListNode *partition(ListNode *head, int x) {
  2. if(head == NULL) return NULL;
  3. ListNode *dummy = new ListNode(-1);
  4. dummy -> next = head;
  5. ListNode *p=head->next;
  6. ListNode *pre = head;
  7. ListNode *q=dummy;
  8. if(head->val < x) q=head;
  9. else q=dummy;
  10. while(p!=NULL) {
  11. if(p->val<x) {
  12. if(p==q->next) {
  13. pre=p;
  14. p=p->next;
  15. q=q->next;
  16. } else{
  17. pre->next=p->next;
  18. p->next=q->next;
  19. q->next=p;
  20. q=q->next;
  21. p=pre->next;
  22. }
  23. } else {
  24. pre=p;
  25. p=p->next;
  26. }
  27. }
  28. return dummy->next;
  29. }
posted @ 2014-08-01 11:21  purejade  阅读(86)  评论(0编辑  收藏  举报