leetcode 118: Partition List
来源:互联网 发布:网络机房建设国家标准 编辑:程序博客网 时间:2024/04/30 14:26
Partition ListApr 30 '12
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. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ //null, {}, {1}x=1, {1,2,3,4} x=3 public class Solution { public ListNode partition(ListNode head, int x) { // Start typing your Java solution below // DO NOT write main() function if(head==null) return null; ListNode low = new ListNode(0); ListNode p = low; ListNode high = new ListNode(0); ListNode q = high; while(head!=null) { int y = head.val; if(y<x) { p.next = head; p = p.next; } else { q.next = head; q = q.next; } head = head.next; } p.next = high.next; q.next = null; return low.next; }}
this approach won't reserve the order of original list, but in-place
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function //1 2 5 3 2 4 ListNode *i=head, *j = head; while(j!=nullptr) { if(j->val<x) { swap(i->val, j->val); i = i->next; } j = j->next; } return head; }};
- leetcode 118: 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]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
- ORA-01000
- V4L2 Linux驱动简介(3)基本I/O原理
- Ext多表头
- 【Android开发学习22】Activity的声明周期--Activity Lifecycle
- 文本框控制输入时分秒的时间格式
- leetcode 118: Partition List
- Jsp中显示当前时间
- No20、(字符串)
- hdu1083
- 之前写的SSL的性能测试程序
- WinDBG 技巧:设置系统默认调试器
- C++ STL next_permutation的实现原理
- curl POST的数据大于1024字节
- WPF 应用程序开机自启动及窗体关闭按钮作用失效的解决办法