[leetcode]86. Partition List劃分鏈表
阿新 • • 發佈:2018-06-26
art HA lee AD 代碼 gre output In origin
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.
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
題意:
給定一個鏈表和一個值,把小於等於和大於該值的部分分別放到鏈表的一前一後去。
思路:
先分為兩個鏈表
然後合並
代碼:
1 class Solution { 2 public ListNode partition(ListNode head, int x) { 3 ListNode leftDummy = new ListNode(-1); 4 ListNode rightDummy = new ListNode (-1); 5 ListNode left_cur = leftDummy; 6 ListNode right_cur = rightDummy;7 ListNode cur = head; 8 9 while( cur != null){ 10 if(cur.val < x){ 11 left_cur.next = cur; 12 left_cur = cur; 13 }else{ 14 right_cur.next = cur; 15 right_cur = cur; 16 }17 cur = cur.next; 18 } 19 left_cur.next = rightDummy.next; 20 right_cur.next = null; 21 return leftDummy.next; 22 }
[leetcode]86. Partition List劃分鏈表