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->null
and x = 3,
return 1->2->2->4->3->5->null
.
将链表分成两个链表,一个奇数一个偶数,最后合并。Memory Limit Exceeded
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) {
if(head == null) return null;
ListNode firstCur = null, secondCur = null, cur = head, firstHead = null, secondHead = null;
while(cur != null) {
if(cur.val < x) {
if(firstCur == null) {
firstCur = cur;
firstHead = cur;
}
else {
firstCur.next = cur;
firstCur = firstCur.next;
}
}
else {
if(secondCur == null) {
secondCur = cur;
secondHead = cur;
}
else {
secondCur.next = cur;
secondCur = secondCur.next;
}
}
cur = cur.next;
}
if(firstCur != null) {
firstCur.next = secondHead;
return firstHead;
}
else {//if there is not nodes less than x
return secondHead;
}
}
}
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) {
if(head == null) return null;
ListNode dummy = new ListNode(0);
ListNode insertPos = dummy;
dummy.next = head;
while(insertPos.next != null && insertPos.next.val < x) {
insertPos = insertPos.next;
}
ListNode cur = insertPos;
while(cur.next != null) {
if(cur.next.val < x) {
ListNode tmp = insertPos.next;
insertPos.next = cur.next;
cur.next = cur.next.next;
insertPos.next.next = tmp;
insertPos = insertPos.next;
}
else
cur = cur.next;
}
return dummy.next;
}
}