86. Partition List
来源:互联网 发布:制作工资表软件 编辑:程序博客网 时间:2024/06/18 04:36
题目:
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
.
给定一个链表,以及一个数字X,将小于X的节点放到链表之前,大于等于X的节点放到链表之后。每个节点在两部分中的相对顺序与原链表中的相同。
思路:
新建左右两部分的头结点,轮训单链表每个节点,将小于X值的节点新加到左边链表上,大于等于X值的节点挂接到右边链表上,之后将右边部分链表连接到左边部分链表后面。
代码:C++版:9ms
/** * 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) { ListNode left_dummy(-1); // 头结点 ListNode right_dummy(-1); // 头结点 auto left_cur = &left_dummy; auto right_cur = &right_dummy; for (ListNode *cur = head; cur; cur = cur->next) { if (cur->val < x) { left_cur->next = cur; left_cur = cur; } else { right_cur->next = cur; right_cur = cur; } } left_cur->next = right_dummy.next; right_cur->next = nullptr; return left_dummy.next; }};
0 0
- [LeetCode]86.Partition List
- LeetCode 86. Partition List
- [Leetcode] 86. Partition List
- LeetCode --- 86. Partition List
- 86. Partition List
- [leetcode] 86.Partition List
- [leetcode] 86. Partition List
- 86. Partition List
- [LeetCode]86. Partition List
- 86. Partition List
- 86. Partition List LeetCode
- 86. Partition List
- 86. Partition List
- 86. Partition List
- Leetcode 86. Partition List
- LeetCode *** 86. Partition List
- LeetCode 86. Partition List
- [LeetCode]86. Partition List
- React知识库内容精选:10篇文章让你迅速了解该框架
- Listview
- pc端vnc连接android 端
- Android工程与web工程通过tomcat服务器建立网络连接案列
- 12-CSS布局模型
- 86. Partition List
- iOS图片的缓存
- LeetCode:Binary Tree Zigzag Level Order Traversal
- iOS快速得到视图的width,height,x,y
- tar命令详解
- 本地如何搭建IPv6环境测试你的APP
- C语言:全局变量在多个c文件中公用的方法
- rtmp ios 编译脚本
- android基于JSON的短信备份功能