Leetcode 86. Partition List

来源:互联网 发布:linux启动ftp服务 编辑:程序博客网 时间:2024/06/05 19:16

Solution 1. 

* Find the first node with value greater or equal to x, 

* then start from this node, find the node that is less than x, 

* insert that node before the first node.

public class Solution {    public ListNode partition(ListNode head, int x) {        if (head == null || head.next == null) {            return head;        }                ListNode dummy = new ListNode(0);        dummy.next = head;        ListNode fast = dummy;        ListNode slow = null;                // find the insertion position        while (fast.next != null) {            if (fast.next.val >= x) {                break;            }            fast = fast.next;        }                slow = fast.next;        // find the previous node of node which val is < x        while (slow != null && slow.next != null) {            if (slow.next.val < x) {                // insert slow.next after fast                ListNode insert = slow.next;                slow.next = insert.next;                ListNode tmp = fast.next;                fast.next = insert;                insert.next = tmp;                fast = fast.next;            } else {                slow = slow.next;            }        }                return dummy.next;    }}

Solution 2.

Maintain two lists, the left list contains all nodes with values < x,

the right list contains all nodes with values >= x.

Concatenate them at the last.

public class Solution {    public ListNode partition(ListNode head, int x) {        // write your code here        ListNode left = new ListNode(0);        // list saves nodes with value < x        ListNode right = new ListNode(0);       // list saves nodes with value >= x        ListNode left_cursor = left;        ListNode right_cursor = right;                        while (head != null) {            if (head.val < x) {                left_cursor.next = head;                left_cursor = head;            } else {                right_cursor.next = head;                right_cursor = head;            }            head = head.next;        }                // concatenate two lists        right_cursor.next = null;        left_cursor.next = right.next;                return left.next;    }}


0 0
原创粉丝点击