-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathT4.java
More file actions
57 lines (50 loc) · 1.45 KB
/
T4.java
File metadata and controls
57 lines (50 loc) · 1.45 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
package testCode;
public class T4 {
public static void main(String[] args) {
System.out.println("Hello World!");
ListNode head = new ListNode(2);
head.next = new ListNode(3);
head.next.next = new ListNode(1);
System.out.print(sortList(head).next.next.val);
}
public static ListNode sortList(ListNode head) {
if (null == head || null == head.next) {
return head;
}
ListNode headStep = head;
ListNode head2Step = head.next;
while (null != head2Step && null != head2Step.next) {
headStep = headStep.next;
head2Step = head2Step.next.next;
}
ListNode l2 = sortList(headStep.next);
headStep.next = null;
ListNode l1 = sortList(head);
ListNode result = new ListNode(0);
ListNode pointer = result;
while (null != l1 && null != l2) {
if (l1.val >= l2.val) {
result.next = l1;
l1 = l1.next;
} else {
result.next = l2;
l2 = l2.next;
}
result = result.next;
}
if (null == l1) {
result.next = l2;
} else {
result.next = l1;
}
return pointer.next;
}
private static class ListNode {
public int val;
public ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
}