Boostable

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  116 随笔 :: 0 文章 :: 28 评论 :: 93229 阅读

LeetCode: 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.

地址:https://oj.leetcode.com/problems/partition-list/

算法:首先,找到第一个大于等于x的节点,记其前趋节点为pre,则在继续往后遍历,若发现比x小的值,则把该节点从链表中移出来,插入到pre节点后面。代码:

复制代码
 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(!head)   return NULL;
13         ListNode *p = head;
14         ListNode *pre = NULL;
15         while(p && p->val < x){
16             pre = p;
17             p = p->next;
18         }
19         if(!p)
20             return head;
21         ListNode *q = NULL;
22         while(p->next){
23             if(p->next->val < x){
24                 q = p->next;
25                 p->next = q->next;
26                 if(pre){
27                     q->next = pre->next;
28                     pre->next = q;
29                     pre = q;
30                 }else{
31                     q->next = head;
32                     head = q;
33                     pre = q;
34                 }
35             }else{
36                 p = p->next;
37             }
38         }
39         return head;
40     }
41 };
复制代码

 

posted on 2014-09-01 22:16  Boostable  阅读(196)  评论(0)    收藏  举报
编辑推荐:
· 聊一聊 Linux 上对函数进行 hook 的两种方式
· C# 锁机制全景与高效实践:从 Monitor 到 .NET 9 全新 Lock
· 一则复杂 SQL 改写后有感
· golang中写个字符串遍历谁不会?且看我如何提升 50 倍
· C# 代码如何影响 CPU 缓存速度?
阅读排行:
· 突发,CSDN 崩了!程序员们开始慌了?
· 一个基于 .NET 8 + Ant Design Blazor 开发的简洁现代后台管理框架
· C# WinForms 实现打印监听组件
· 鸿蒙Next仓颉语言开发实战教程:订单详情
· 网易游戏DB SaaS引入OceanBase:存储成本降60%,备份恢复提速3倍
点击右上角即可分享
微信分享提示