LeeCode partition List
来源:互联网 发布:网络转盘游戏 编辑:程序博客网 时间:2024/05/16 18:09
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.
class Node{private int val; Node next;public Node(int val) {this.val = val;this.next = null;}}
public Node partition(Node head, int x) {Node fakeNode1 = new Node(0);fakeNode1.next = head;Node fakeNode2 = new Node(0);Node p = fakeNode1;Node n = fakeNode2; while(p.next!=null){if(p.next.val<x){Node after = p.next.next ; Node cur = p.next;p.next = after;n.next = cur;n = n.next;}else{p = p.next;}} n.next = fakeNode1.next;return fakeNode2.next;}
先创建2个头指针分别指向大于x的Node节点组成的List 和小于x的Node节点组成的List的头节点
遍历时,如果遇到大于x值的直接往后移一位,如果遇到小于x值的那么就把那个小于x值的节点取出来
放入另一个List中。 p 和n 分别用来跟踪两个List的Node。结束后将他们接起来。时间复杂O(n)。
0 0
- leecode Partition List
- LeeCode partition List
- [leecode][List][two pointers] Partition List
- leecode 解题总结:86. Partition List
- [LeeCode] Insertion Sort List
- [Leecode 61] Rotate List
- Leecode-Linked List Cycle
- LeeCode 148 Sort List
- LeeCode 61 Rotate List
- [Leecode]Linked List CycleII
- LeeCode-Linked List Cycle
- LeeCode-Insertion Sort List
- leecode - Reverse Linked List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- 矫情的人生
- CSS3 Gradient 渐变
- 第二周作业
- android studio——Failed to set up SDK
- PHP字符串赋值
- LeeCode partition List
- 代码规范
- 开通博客的第一天
- 使用 Open XML SDK 2.0 从 Word 2010 文档中提取样式
- android获取连接到手机热点上的设备的信息
- jQuery 垂直滑动新闻展示
- jbpm fork join
- Memcached旅终结
- RequestDispatcher的使用