LeetCode OJ - Partition List
来源:互联网 发布:鬼才大小姐 知乎 编辑:程序博客网 时间:2024/05/17 23:05
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
.
分析:快排的的基本操作,因为是链表,所以可以采用单向遍历来划分区间,其中交换操作用插入删除代替。
思路一:small指针和cur指针,若cur < x,那么cur插入到small之后
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *remove1(ListNode * last, ListNode *cur) { if(!cur) return NULL; last->next = cur->next; cur->next = NULL; return cur; } void insert(ListNode *small, ListNode *node) { if(!node) return ; node->next = small->next; small->next = node; } ListNode *partition(ListNode *head, int x) { if(!head) return NULL; ListNode dummy(0); dummy.next = head; ListNode *small = &dummy; while(small->next && small->next->val < x) { small = small->next; } ListNode *cur = small->next; ListNode *last = small; while(cur) { if(cur->val < x) { ListNode *node = remove1(last, cur); cur = last; insert(small, node); small = small->next; } last = cur; cur = cur->next; } return dummy.next; }};
思路二:head指针和tail指针,tail指针指向末尾,大于等于x的插入tail之后
思路三:构建两个链表,一个小区链表,一个大区链表,最后合并。数组之所以不这样,是因为会使用额外空间。
0 0
- LeetCode OJ:Partition List
- LeetCode OJ - Partition List
- LeetCode OJ Partition List
- <LeetCode OJ> 61 / 86 Rotate List / Partition List
- LeetCode OJ 之 Partition List (划分链表)
- LeetCode: Partition List
- LeetCode Partition List
- LeetCode: Partition List
- [Leetcode] Partition List **
- [Leetcode] Partition List
- [LeetCode] Partition List
- leetcode 81: Partition List
- [Leetcode] Partition List
- leetcode 118: Partition List
- [LeetCode]Partition List
- [leetcode]Partition List
- LeetCode-Partition List
- [leetcode] Partition List
- Atmega90can32/64/128串口详解(二)
- Notepad++背景颜色设置
- 网页设计工具
- 搜索引擎优化网页设计:最佳实践
- poj 1852 蚂蚁问题,很经典,实际上就是找最靠近边缘和最靠近中间,靠近边缘要注意小数的处理
- LeetCode OJ - Partition List
- Source Insight如何改变背景颜色
- 为什么我要开始写点东西
- 小应用程序求100之内的所有素数
- 把UIView切成任意形状
- poj 1363 火车进站问题,栈的基本应用
- struts2表单验证里field-validator type值一共可以取哪些?都什么含义?
- iis6+php设置重写
- Android五大布局