LeetCode - Partition List
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                LeetCode - Partition List
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.                        
                                題目:
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. 
思路:
分成兩個(gè)鏈表,然后鏈接
package list;public class PartitionList {public ListNode partition(ListNode head, int x) {ListNode leftNode = new ListNode(0);ListNode rightNode = new ListNode(0);ListNode p = leftNode;ListNode q = rightNode;while (head != null) {if (head.val < x) {leftNode.next = head;leftNode = leftNode.next;} else {rightNode.next = head;rightNode = rightNode.next;}head = head.next;}rightNode.next = null;leftNode.next = q.next;return p.next;}public static void main(String[] args) {// TODO Auto-generated method stubListNode a1 = new ListNode(1);ListNode a2 = new ListNode(4);ListNode a3 = new ListNode(3);ListNode a4 = new ListNode(2);ListNode a5 = new ListNode(5);ListNode a6 = new ListNode(2);a1.next = a2;a2.next = a3;a3.next = a4;a4.next = a5;a5.next = a6;a6.next = null;PartitionList p = new PartitionList();ListNode head = p.partition(a1, 3);while (head != null) {System.out.println(head.val);head = head.next;}}}?
轉(zhuǎn)載于:https://www.cnblogs.com/null00/p/5097715.html
總結(jié)
以上是生活随笔為你收集整理的LeetCode - Partition List的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
                            
                        - 上一篇: 虚拟机安装CentOS6.4
 - 下一篇: 团队项目冲刺第三天