-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathq086_PartitionList.java
More file actions
73 lines (65 loc) · 1.98 KB
/
q086_PartitionList.java
File metadata and controls
73 lines (65 loc) · 1.98 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package leetcode_algorithm;
/**
* 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.
* <p>
* You should preserve the original relative order of the nodes in each of the two partitions.
* <p>
* For example,
* Given 1->4->3->2->5->2 and x = 3,
* return 1->2->2->4->3->5.
*/
public class q086_PartitionList {
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(4);
ListNode l3 = new ListNode(3);
ListNode l4 = new ListNode(2);
ListNode l5 = new ListNode(5);
ListNode l6 = new ListNode(2);
l1.next = l2;
l2.next = l3;
l3.next = l4;
l4.next = l5;
l5.next = l6;
q086_PartitionList solution = new q086_PartitionList();
System.out.println(solution.partition(l1, 3));
ListNode s1 = new ListNode(2);
ListNode s2 = new ListNode(1);
s1.next = s2;
System.out.println(solution.partition(s1, 2));
}
/**
* 解法1
*
* @param head
* @param x
* @return
*/
public ListNode partition(ListNode head, int x) {
ListNode dummy1 = new ListNode(0), dummy2 = new ListNode(0);//两个链表的头结点
ListNode curr1 = dummy1, curr2 = dummy2; //两个链表的尾节点
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 = dummy2.next;//将两个链表结合
return dummy1.next;
}
private static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
public String toString() {
return val + (next != null ? "->" + next.toString() : "");
}
}
}