算法系列——Partition List
来源:互联网 发布:雷姆雷姆软件汉化版 编辑:程序博客网 时间:2024/05/16 04:41
题目描述
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.
解题思路
这道题要求将链表分成两个部分,使得所有小于给定值的节点在链表前面,大于等于给定值的节点在链表后面。
采用两个虚拟头结点 ,会使题目非常简单。一节点用来连接小于给定值的部分,另外节点用于连接大于等于给定值的部分,遍历原链表,拿链表中的值和给定值进行比较,按照条件连接到两个虚拟节点尾部即可,最后将这两个链表连接起来。
程序实现
public class Solution { public ListNode partition(ListNode head, int x) { if(head==null||head.next==null) return head; ListNode dummy1=new ListNode(-1); ListNode dummy2=new ListNode(-1); ListNode p1=dummy1; ListNode p2=dummy2; ListNode p=head; while(p!=null){ if(p.val<x){ p1.next=p; p1=p1.next; }else{ p2.next=p; p2=p2.next; } p=p.next; } p2.next=null; p1.next=dummy2.next; return dummy1.next; }}
阅读全文
0 0
- 算法系列——Partition List
- LeetCode86——Partition List
- 链表——partition list
- Algorithms—86.Partition List
- LeetCode算法题目:Partition List
- 算法系列——Reverse Linked List
- 算法系列——Linked List Cycle
- 算法系列——Sort List
- 算法系列——Rotate List
- 算法系列——Reorder List
- leetcode 086 —— Partition List
- Leetcode——86. Partition List
- 2.2.3—单链表— Partition List
- LeetCode 之 Partition List — C++ 实现
- [leetcode刷题系列]Partition List
- leetcode系列(67)Partition List
- Leetcode算法学习日志-86 Partition List
- 算法系列—— Reverse Linked List II
- Linux与Windows平台无关后台服务应用程序实现
- 透明显示屏
- 用SetUpDi系列函数获得系统设备信息
- Servlet初步
- Eratosthenes筛法(素数筛法)
- 算法系列——Partition List
- HashTable----- List 299. Bulls and Cows
- Mysql 查询缓存
- Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'. > com.android.bui
- Android_ADB_通过WIFI或USB方式完成调试
- ubuntu双系统安装
- 利用freemaker和ftl文件导出word带不开的问题
- 机器学习(十三)- Backpropagation in Practice
- live555与vlc的rtsp组播交互信息(Log)