Given a linked list and a value x, partition it such that all nodes less than x come before nodes greate R than or equal to x.
You should preserve the original relative order of the nodes in each of the.
For example,
Given 1->4->3->2->5->2 and x = 3,
Return 1->2->2->4->3->5 .
Problem Solving Ideas:
Just record the last pointer less than 3 and the first pointer greater than 3, and, if you create a listnode result pointing head can reduce the code length, this gives the simplest Java implementation:
Public ListNode partition (ListNode head, int x) {if (head = = NULL | | head.next = = NULL) return head; ListNode temp = head, Firstmin = head;if (head.val >= x) {while (firstmin.next! = null) {if (FirstMin.next.val < x) {head = Firstmin.next;firstmin.next = Firstmin.next.next;head.next = Temp;break;} Firstmin = Firstmin.next;}} if (head.val >= x) return head;firstmin = Head;temp=head.next;while (temp! = null && temp.val < x) {Firstmin = Firstmin.next;temp = Temp.next;} if (Temp==null) return head; ListNode Firstmax=temp,lastmax=temp;temp=temp.next;while (temp!=null) {if (temp.val<x) {firstMin.next=temp; Firstmin=firstmin.next;} Else{lastmax.next=temp;lastmax=lastmax.next;} Temp=temp.next;} Firstmin.next=firstmax;lastmax.next=null;return Head;}
Java for Leetcode 086