leetcode [86]Partition List
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:
Input: head = 1->4->3->2->5->2, x = 3 Output: 1->2->2->4->3->5
题目大意:
将LinkedList利用partition划分为两个部分,LinkedList的前半部分都是比给定的x要小的值,而后半部分是比给定值要大的值。
解法:
将该链表一分为二,分成两个链表,最后再将两个链表串起来。链表一存放的都是比value值要小的节点,而链表二存放的都是比value值要大的节点。
java:
class Solution { public ListNode partition(ListNode head, int x) { ListNode h1=new ListNode(0); ListNode h2=new ListNode(0); ListNode head1=h1,head2=h2; while(head!=null){ if(head.val<x){ head1.next=head; head1=head1.next; }else{ head2.next=head; head2=head2.next; } head=head.next; } head2.next=null; head1.next=h2.next; return h1.next; } }