链表划分

来源:互联网 发布:js attr style 编辑:程序博客网 时间:2024/06/03 18:04

题目

给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。

你应该保留两部分内链表节点原有的相对顺序。
样例
给定链表 1->4->3->2->5->2->null,并且 x=3

返回 1->2->2->4->3->5->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) {        // write your code here        if(head == null || head.next == null)            return head;        ListNode p = head;        ListNode leftDummy = new ListNode(0);        ListNode rightDummy = new ListNode(0);        ListNode left = leftDummy, right = rightDummy;        while (p != null) {            if (p.val < x) {                left.next = p;                left = p;            } else {                right.next = p;                right = p;            }            p = p.next;        }        right.next = null;        left.next = rightDummy.next;        return leftDummy.next;    }}
0 0