leetcode【第八周】链表划分
来源:互联网 发布:网络虚拟手机号发短信 编辑:程序博客网 时间:2024/06/09 16:11
问题描述:
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
.
问题分析:
不难想到,构建两个链表,顺序读取原链表,值小于阙值的节点和大于等于阙值的节点分别按顺序放到两个新链表中,最后再将小于阙值的链表尾指向大于等于阙值的链表头。值得注意的是,最后要把大于等于阙值的链表最后一个节点的指针指向空,以防循环。
代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* partition(ListNode* head, int x) { if(head==NULL) return NULL; ListNode* litterHead = new ListNode(0); ListNode* litter = litterHead; ListNode* greaterHead = new ListNode(0); ListNode* greater = greaterHead; ListNode* curr = head; while(curr) { if(curr->valnext = curr; litter = litter->next; curr = curr->next; }else { greater->next = curr; greater = greater->next; curr = curr->next; } } greater->next = NULL; litter->next = greaterHead->next; return litterHead->next; }};
0 0
- leetcode【第八周】链表划分
- [LeetCode]86 链表划分
- Partition List 链表划分区间@LeetCode
- LeetCode(Partition List) 划分链表
- Leetcode 86. Partition List(链表划分)
- 【LeetCode】Partition List 链表划分
- leetcode-python 第八周
- leetcode-第八周
- 第八周leetcode题
- 第八周LeetCode
- 第八周LeetCode
- [leetcode]第八周作业
- LeetCode题解 第八周
- LeetCode OJ 之 Partition List (划分链表)
- leetcode 86. Partition List-链表划分|双指针
- Leetcode 86. Partition List 链表划分 解题报告
- LeetCode 86. Partition List 链表的划分 Python Solution
- leetcode第八周解题总结
- [学习笔记]设计模式[b]-{与设计模式相处}
- Linux之VMtools的安装方法
- 浅谈千万级PV/IP规模高性能高并发网站架构
- asp.net引用类库dll文件
- 自考总结
- leetcode【第八周】链表划分
- JAVA 中native关键字
- oralce命令行与简单查询
- poj 1745 Divisibility dp
- 自定义View_绘制圆_进行拖动(不出屏幕)放大缩小
- setTimeout机制的思考
- 区间DP
- Cesium应用篇:3控件(5)CesiumInspector
- Java 泛型