题目链接
法一
public ListNode partition(ListNode head, int x) {
ListNode dummy = new ListNode(0, head);
ListNode tail = dummy, pre = dummy, cur = head;
while (cur != null) {
if (cur.val < x) {
pre.next = cur.next;
cur.next = tail.next;
tail.next = cur;
tail = tail.next;
}
pre = cur;
cur = cur.next;
}
return dummy.next;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
本地测试
lay.showTitle(86);
Solution86 sol86 = new Solution86();
int[] nums86 = new int[]{1, 4, 3, 2, 5, 2};
ListNode head86 = new ListNode();
head86 = listOpt.creatListByArray(head86, nums86);
listOpt.showList(head86);
int x86 = 3;
System.out.println(x86);
head86 = sol86.partition(head86.next, x86);
listOpt.showNoHeadList(head86);