partition-list Java code

来源:互联网 发布:editplus php代码提示 编辑:程序博客网 时间:2024/05/20 19:17

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,
Given1->4->3->2->5->2and x = 3,
return1->2->2->4->3->5.

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode partition(ListNode head, int x) {        if(head==null)            return null;        ListNode dummy1=new ListNode(0);        ListNode dummy2=new ListNode(0);        ListNode curr1=dummy1;        ListNode curr2=dummy2;        while(head!=null){            if(head.val<x){                curr1.next=head;                curr1=curr1.next;            }else{                curr2.next=head;                curr2=curr2.next;            }            head=head.next;        }        curr2.next=null;        curr1.next=dummy2.next;        return dummy1.next;    }}