[LeetCode]Partition List
来源:互联网 发布:switch网络一会b一会f 编辑:程序博客网 时间:2024/06/05 19:35
题目描述
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的节点全部移到他们俩之间。
代码
public static ListNode partition(ListNode head, int x) {ListNode loopNode = head;ListNode firstGreaterOrEqualXNode = null;ListNode beforeFirstGreaterOrEqualXNode = null;ListNode tempNode = null;ListNode result = head;//找到第一个大于或等于x的节点和它之前的那个节点while (loopNode != null && loopNode.val < x) {beforeFirstGreaterOrEqualXNode = loopNode;loopNode = loopNode.next;}firstGreaterOrEqualXNode = loopNode;if (loopNode != null) {while (loopNode.next != null) {if (loopNode.next.val < x) {tempNode = loopNode.next;loopNode.next = tempNode.next;if (beforeFirstGreaterOrEqualXNode != null) {//第一个大于或等于x的节点和它之前的那个节点之间插入节点beforeFirstGreaterOrEqualXNode.next = tempNode;} else {//如果第一个大于或等于x的节点是头节点的话result = tempNode;}tempNode.next = firstGreaterOrEqualXNode;beforeFirstGreaterOrEqualXNode = tempNode;} else {//如果当前节点大于x则继续循环loopNode = loopNode.next;}}}return result;}
0 0
- 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
- LeetCode - Partition List
- [LeetCode] Partition List
- LeetCode 86: Partition List
- LeetCode:Partition List
- 【leetcode】Partition List
- Java Proxy InvocationHandler invoke理解
- MFC下unsigned char和Cstring的转换
- 智能手表开发API接口之我见
- 如何在VS 编译器下 使用纯 C 语言编译器?
- Junit 入门(二)
- [LeetCode]Partition List
- ComboBox消息打开列表
- 安卓实训第九天---Activity的复习以及在Onstart里设置网络连接
- 没有方向了?
- Stopping and Restarting an Activity 停止和重新启动活动
- WIN7下VMware+Ubuntu配置上网(对无线网络也有效)
- [二次开发] 饭窝网重磅出击 “图文菜谱discuz二次开发应用”
- 使用CountdownTimer进行倒计时
- 排序(二)键索引、桶排序、位示图、败者树等(图文详解--败者树)