/*
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.
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
/*
key to solve:
Use two linked list:
lS store for all nodes less than x;
lL store for all nodes greater than or equal to x;
combine two Linked lists together in the end
becareful: remember to close the Linkedlist for end of lL Linked list
otherwise, it will cause infinity cycle
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if(head==null || head.next==null) return head;
ListNode lS=new ListNode(0);
ListNode lL=new ListNode(0);
//save the head of both lS and lL Linked list
ListNode lShead=lS;
ListNode lLhead=lL;
while(head!=null){
if(head.val<x){
//connect lS.next with the (head.val < x)
lS.next=head;
//move to next node of lS
lS=lS.next;
}else{
//head.val>=x
lL.next=head;
//move to next node of lL
lL=lL.next;
}
//move head to next node
head=head.next;
}
//*important*close the lL Linked list
lL.next=null;
//combine to two linked list
lS.next=lLhead.next;
//return head of lS list
return lShead.next;
}
}
Partition List
最新推荐文章于 2019-03-02 15:26:44 发布