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
.
是一道基本编程题,锻炼对单向链表的操作。
我稍微简化了下程序:
public ListNode partition(ListNode head, int x) {
if (head == null) {
return null;
}
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode node1 = newHead;
ListNode pre = null;
ListNode node2 = head;
while (node2 != null) {
if (node2.val < x) {
if (node1.next != node2) {
pre.next = node2.next;
ListNode oldNodeNext = node1.next;
node1.next = node2;
node2.next = oldNodeNext;
node1 = node2;
node2 = pre.next;
} else {
node1 = node2;
pre = node2;
node2 = node2.next;
}
} else {
pre = node2;
node2 = node2.next;
}
}
return newHead.next;
}
老程序:
public ListNode partition(ListNode head, int x) {
// Start typing your Java solution below
// DO NOT write main() function
if (head == null) {
return null;
}
ListNode newHead = new ListNode(x-1);
newHead.next = head;
ListNode node = newHead;
ListNode pre = newHead;
while (node != null && node.val < x) {
pre = node;
node = node.next;
}
node = pre;
ListNode node2 = node.next;
pre = node;
while (node2 != null) {
if (node2.val < x) {
pre.next = node2.next;
ListNode oldNodeNext = node.next;
node.next = node2;
node2.next = oldNodeNext;
node = node2;
node2 = pre.next;
} else {
pre = node2;
node2 = node2.next;
}
}
return newHead.next;
}