Chinaunix首页 | 论坛 | 博客
  • 博客访问: 40208
  • 博文数量: 37
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 372
  • 用 户 组: 普通用户
  • 注册时间: 2013-10-12 23:27
文章分类

全部博文(37)

文章存档

2014年(5)

2013年(32)

我的朋友

分类: C/C++

2014-01-02 14:06:25

遍历链表将比给定值大或相等的节点移到一个新链表里面,最后新旧链表首尾想接即可。

点击(此处)折叠或打开

  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.         if(NULL==head) return NULL;
  13.         ListNode *bigger_head=NULL;
  14.         ListNode *bigger_curr=NULL;
  15.         ListNode *curr=head;
  16.         ListNode *pre=NULL;
  17.         ListNode *re=head;
  18.         while(curr)
  19.         {
  20.             if(curr->val>=x)
  21.             {
  22.                 if(curr==re) re=curr->next;
  23.                 if(NULL==bigger_head) bigger_head=curr;
  24.                 if(pre) pre->next=curr->next;
  25.                 if(bigger_curr) bigger_curr->next=curr;
  26.                 bigger_curr=curr;
  27.                 curr=curr->next;
  28.                 continue;
  29.             }
  30.             pre=curr;
  31.             curr=curr->next;
  32.         }
  33.         if(bigger_curr) bigger_curr->next=NULL;
  34.         if(pre)pre->next=bigger_head;
  35.         return re?re:bigger_head;
  36.     }
  37. };

阅读(189) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~