leetcode [#86] | GCidea's blog
目录

题目
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.
Example:
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
解决方案
1 | /** |
注意事项
- 遍历一遍,将小于x的放在一个ArrayList中,将大于等于x的放在另一个ArrayList中。之后再分别构造链表,相连起来。
- 思路相同,但是不必放入List在连起来构造链表,这样效率比较低。下面方法直接用指针完成:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19public ListNode partition(ListNode head, int x) {
ListNode head1 = new ListNode(0);
ListNode head2 = new ListNode(0);
ListNode curr1 = head1;
ListNode curr2 = head2;
while (head != null){
if (head.val < x) {
curr1.next = head;
curr1 = head;
}else {
curr2.next = head;
curr2 = head;
}
head = head.next;
}
curr2.next = null;
curr1.next = head2.next;
return head1.next;
}