博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 86. Partition List
阅读量:4695 次
发布时间:2019-06-09

本文共 1234 字,大约阅读时间需要 4 分钟。

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.

类似于款速排序中的分割算法。

因为是链表,不能使用从两头向中间扫描,而应使用从前向后扫描,详见算法导论 快速排序。

 

1 ListNode *partition(ListNode *head, int x)  2     { 3         ListNode dummy = ListNode(INT_MIN), *p, *q, *r; 4         dummy.next = head; 5          6         p = &dummy; 7         q = &dummy; 8         while (p->next != NULL) 9         {10             if (p->next->val < x)11             {12                 if (p == q)13                 {14                     p = p->next;15                     q = q->next;16                 }17                 else18                 {19                     r = p->next;20                     p->next = r->next;21                     r->next = q->next;22                     q->next = r;23                     q = r;24                 }25             }26             else27             {28                 p = p->next;29             }30         }31         32         return dummy.next;33     }

转载于:https://www.cnblogs.com/ym65536/p/4148032.html

你可能感兴趣的文章
31、任务三十一——表单联动
查看>>
python之hasattr、getattr和setattr函数
查看>>
maven使用阿里镜像配置文件
查看>>
Copy code from eclipse to word, save syntax.
查看>>
arguments.callee的作用及替换方案
查看>>
23 Java学习之RandomAccessFile
查看>>
P2709 小B的询问
查看>>
PHP echo 和 print 语句
查看>>
第一讲 一个简单的Qt程序分析
查看>>
Centos 6.5下的OPENJDK卸载和SUN的JDK安装、环境变量配置
查看>>
poj 1979 Red and Black(dfs)
查看>>
【.Net基础03】HttpWebRequest模拟浏览器登陆
查看>>
zTree async 动态参数处理
查看>>
Oracle学习之常见错误整理
查看>>
数据库插入数据乱码问题
查看>>
altium annotate 选项设置 complete existing packages
查看>>
【模式识别与机器学习】——SVM举例
查看>>
【转】IT名企面试:微软笔试题(1)
查看>>
IO流入门-第十章-DataInputStream_DataOutputStream
查看>>
DRF的分页
查看>>