Partition List
来源:互联网 发布:matlab读取数据和文件 编辑:程序博客网 时间:2024/05/01 15:47
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.
Example
Given 1->4->3->2->5->2->null
and x = 3
,
return 1->2->2->4->3->5->null
.
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The first node of linked list. * @param x: an integer * @return: a ListNode */ public ListNode partition(ListNode head, int x) { if(head == null || head.next == null) { return head; } ListNode leftDummy = new ListNode(0); ListNode rightDummy = new ListNode(0); ListNode left = leftDummy, right = rightDummy; //use left node to connect all nodes that are < x //use right node to connect all nodes that are >= x while (head != null) { if (head.val < x) { left.next = head;//equals to leftdummy.next = head; //leftdummy and left are seperate now, cause left = head //so the leftdummy will be at the head of the left list left = head; } else { right.next = head; //same to the rightdummy and the right node right = head; } head = head.next; } right.next = null; left.next = rightDummy.next; return leftDummy.next; }}
用left 和 right指针来链接node
0 0
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- spring读取加载properties文件
- Linux git服务器http方式搭建
- iOS设置状态栏颜色
- 数据库的事务、事务并发以及隔离级别
- SQL state [99999]; error code [17001]; 问题处理
- Partition List
- 关于Java的File.separator
- Java日期与String转换等处理
- jsp--include指令和动作在动态引入中的区别
- sqlplus登录\连接命令、sqlplus命令的使用大全
- JavaScript ES6 核心功能一览
- margin后边的参数个数大解析
- 8000 sentences of Oral English(three)
- LeetCode462. Minimum Moves to Equal Array Elements II