题目链接:https://leetcode.com/problems/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.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
思路:
先把两类结点保存,然后统一链接。时间复杂度O(n),空间复杂度O(n)。
算法:
public ListNode partition(ListNode head, int x) {
ListNode p = head, h1 = null, r2 = null, r1 = null, h2 = null;
List<Integer> l1 = new ArrayList<Integer>();
List<Integer> l2 = new ArrayList<Integer>();
while (p != null) {
if (p.val < x) {
l1.add(p.val);
} else {
l2.add(p.val);
}
p = p.next;
}
Iterator<Integer> i1 = l1.iterator();
while (i1.hasNext()) {
if (h1 == null) {
h1 = new ListNode((Integer) i1.next());
r1 = h1;
} else {
r1.next = new ListNode((Integer) i1.next());
r1 = r1.next;
}
}
Iterator<Integer> i2 = l2.iterator();
while (i2.hasNext()) {
if (h2 == null) {
h2 = new ListNode((Integer) i2.next());
r2 = h2;
} else {
r2.next = new ListNode((Integer) i2.next());
r2 = r2.next;
}
}
if (r1 != null) {
r1.next = h2;
head = h1;
} else {
head = h2;
}
return head;
}
思路二:
将两类各自结点链接,最后合并。时间复杂度O(n),空间复杂度O(1)
算法二:
public ListNode partition(ListNode head, int x) {
ListNode lessHead = new ListNode(0);
ListNode greaterHead = new ListNode(0);
ListNode node = head, less = lessHead, greater = greaterHead;
while (node != null) {
ListNode next = node.next;
if (node.val < x) {
less.next = node;
less = less.next;
less.next = null;
} else {
greater.next = node;
greater = greater.next;
greater.next = null;
}
node = next;
}
less.next = greaterHead.next;
return lessHead.next;
}