题目地址:https://leetcode.com/problems/partition-list/description/
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
.
这个题目是对链表进行分区,熟悉快排算法的童鞋很快就发现,这个可以用在对链表进行快速排序。
链表和数组最大的区别就在随机访问元素的时间复杂度。所以对于这个题目,但是链表也有它自己的好处,那就是不用在内存中开辟整块空间,所以在这里遍历原始链表,可以新建两个链表分别存储小于x和大于等于x的节点,然后将讲个链表拼接起来就可以了。
public class PartitionList {
public static ListNode partition(ListNode head, int x) {
if (head == null)
return null;
ListNode head1 = new ListNode(0);
ListNode head2 = new ListNode(0);
ListNode p = head;
ListNode q = head1;
ListNode k = head2;
while (p != null) {
if (p.val < x) {
q.next = p;
q = q.next;
} else {
k.next = p;
k =k.next;
}
p = p.next;
}
q.next = head2.next;
k.next = null;
return head1.next;
}
public static void printList(ListNode head) {
if (head == null)
return;
ListNode p = head;
while (p != null) {
System.out.print(p.val + "->");
p = p.next;
}
System.out.println("null");
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(4);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(2);
head.next.next.next.next = new ListNode(5);
head.next.next.next.next.next = new ListNode(2);
printList(partition(head, 2));
return;
}
}