码迷,mamicode.com
首页 > 其他好文 > 详细

86.Partition List

时间:2015-12-06 22:28:45      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

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小的链表节点都出现在比x大或者等于的节点前面,而且还要保持原来的相对位置不要发生变化。我们新建两个链表了l1,l2,遍历原来的链表 ,把值小于x的节点都加入l1,把值大于或者等于x的节点都加入l2,最后将l2连接至l1的后面,所得的链表就是我们所求的结果了。
  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode* partition(ListNode* head, int x) {
  12. ListNode *head1,*head2;
  13. head1=head2=NULL;
  14. ListNode *cur1,*cur2;
  15. cur1=cur2=NULL;
  16. while(head){
  17. ListNode *cur=head;
  18. head=head->next;
  19. cur->next=NULL;
  20. if(cur->val<x){
  21. if(!head1){
  22. head1=cur;
  23. cur1=head1;
  24. }
  25. else{
  26. cur1->next=cur;
  27. cur1=cur1->next;
  28. }
  29. }else{
  30. if(!head2){
  31. head2=cur;
  32. cur2=head2;
  33. }else{
  34. cur2->next=cur;
  35. cur2=cur2->next;
  36. }
  37. }
  38. }
  39. if(!cur1)
  40. return head2;
  41. cur1->next=head2;
  42. return head1;
  43. }
  44. };

 




86.Partition List

标签:

原文地址:http://www.cnblogs.com/zhoudayang/p/5024432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!