LeetCode 66 Partition List
来源:互联网 发布:snmp监控返回端口号 编辑:程序博客网 时间:2024/04/29 00:55
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.
分析:
这就是快速排序的思路,不过是在链表上进行,维护一个tail指针,之前放的都是小于x的节点,往后遍历一遍,碰见>=x的跳过,碰见<x的移到tail后面,再把tail后移一位。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode partition(ListNode head, int x) { ListNode newHead = new ListNode(0); newHead.next = head; ListNode tail = newHead; ListNode p = newHead; while(p.next != null){ if(p.next.val < x){ if(p==tail){//no need to move tail = tail.next; p = p.next; }else{ ListNode tmp = p.next; p.next = p.next.next;//delete tmp.next = tail.next;//insert after tail tail.next = tmp; tail = tail.next; } }else{ p = p.next; } } return newHead.next; }}
0 0
- LeetCode 66 Partition List
- 66 leetcode - 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
- LeetCode - Partition List
- [LeetCode] Partition List
- LeetCode 86: Partition List
- [Vijos P1842] Noip2013Day1T2
- 对一块扁平内存进行划分,并用链表串起来
- Oracle本地管理对比数据字典管理表空间
- 熊孩子不肯坐安全座椅?试试以下方法
- fdisk分区时无效参数错误解决办法
- LeetCode 66 Partition List
- Servlet模拟网上售票问题,解决线程的安全问题
- Lucene评分机制
- Android.mk for your own module [M
- EasyBCD在windows7基础上安装Ubuntu 14.04双系统详
- trie tree
- Memory barrier——WiKi
- [LeetCode] Valid Sudoku Partition List
- JS中prototype的实例