Partition List

来源:互联网 发布:matlab读取数据和文件 编辑:程序博客网 时间:2024/05/01 15:47

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.

Example

Given 1->4->3->2->5->2->null and x = 3,
return 1->2->2->4->3->5->null.


/** * Definition for ListNode. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int val) { *         this.val = val; *         this.next = null; *     } * } */ public class Solution {    /**     * @param head: The first node of linked list.     * @param x: an integer     * @return: a ListNode      */    public ListNode partition(ListNode head, int x) {        if(head == null || head.next == null) {            return head;        }        ListNode leftDummy = new ListNode(0);        ListNode rightDummy = new ListNode(0);        ListNode left = leftDummy, right = rightDummy;        //use left node to connect all nodes that are < x        //use right node to connect all nodes that are >= x        while (head != null) {            if (head.val < x) {                left.next = head;//equals to leftdummy.next = head;                //leftdummy and left are seperate now, cause left = head                //so the leftdummy will be at the head of the left list                left = head;            } else {                right.next = head;                //same to the rightdummy and the right node                right = head;            }            head = head.next;        }                right.next = null;        left.next = rightDummy.next;        return leftDummy.next;    }}

用left 和 right指针来链接node

0 0
原创粉丝点击