標籤:des style class blog code ext
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.
Analysis: Linked List 慣用套路,Runner Technique(Two Pointers), 一些技巧就是:設定head的前置假節點prev,兩個pointer:current和runner都指到這個prev,然後進行判斷總是判斷 current.next 或者 runner.next. 這樣做按照我多次做類似題的經驗來說,是最方便省事不容易出錯的。這道題一次過。思路就是current 和 runner 一直移動直到找到 current.next >= x 為止,這裡就是後面小於x的元素將要插入的位置,current便停在這裡,指示這個位置,runner繼續往後面尋找,把每一個小於x的元素都插入到current.next 的位置。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * }10 * }11 */12 public class Solution {13 public ListNode partition(ListNode head, int x) {14 ListNode prev = new ListNode(-1);15 prev.next = head;16 ListNode current = prev;17 ListNode runner = prev;18 while (current.next != null && current.next.val < x) {19 current = current.next;20 runner = runner.next;21 }22 while (runner.next != null) {23 if (runner.next.val < x) {24 ListNode temp = runner.next;25 runner.next = runner.next.next;26 temp.next = current.next;27 current.next = temp;28 current = current.next;29 }30 else runner = runner.next;31 }32 return prev.next;33 }34 }