Leetcode: Partition List

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 }

 

 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 dummy = new ListNode(-1);

15         dummy.next = head;

16         ListNode cur = dummy;

17         ListNode runner;

18         while (cur.next != null && cur.next.val < x) {

19             cur = cur.next;

20         }

21         runner = cur;

22         while (runner.next != null) {

23             if (runner.next.val < x) {

24                 ListNode next = runner.next.next;

25                 runner.next.next = cur.next;

26                 cur.next = runner.next;

27                 cur = cur.next;

28                 runner.next = next;

29             }

30             else runner = runner.next;

31         }

32         return dummy.next;

33     }

34 }

 

 

你可能感兴趣的:(partition)