-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain148.java
More file actions
114 lines (109 loc) · 3.27 KB
/
Main148.java
File metadata and controls
114 lines (109 loc) · 3.27 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package HOT100;
public class Main148 {
public ListNode sortList(ListNode head) {
return sortList(head, null);
}
public ListNode sortList(ListNode head, ListNode tail){
if(head == null){
return null;
}
if(head.next == tail){
head.next=null;
return head;
}
ListNode slow = head, fast = head;
while(fast != tail){
slow = slow.next;
fast = fast.next;
if(fast != tail){
fast = fast.next;
}
}
ListNode mid = slow;
ListNode list1 = sortList(head, mid);
ListNode list2 = sortList(mid, tail);
ListNode sorted = merge(list1, list2);
return sorted;
}
public ListNode merge(ListNode head1, ListNode head2){
ListNode dummyHead = new ListNode(0);
ListNode temp = dummyHead, temp1 = head1, temp2 = head2;
while (temp1 !=null && temp2!=null){
if(temp1.val <= temp2.val){
temp.next = temp1;
temp1 = temp1.next;
}else{
temp.next = temp2;
temp2 = temp2.next;
}
temp = temp.next;
}
if(temp1!=null){
temp.next=temp1;
}else if(temp2!=null){
temp.next=temp2;
}
return dummyHead.next;
}
}
class Main148_1{
public ListNode sortList(ListNode head){
if(head == null){
return null;
}
int length = 0;
ListNode node = head;
while(node != null){
length++;
node = node.next;
}
ListNode dummyHead = new ListNode(0, head);
for(int subLength=1; subLength<length; subLength<<=1){
ListNode prev = dummyHead, curr = dummyHead.next;
while(curr != null){
ListNode head1 = curr;
for (int i=1; i<subLength && curr.next!=null; i++){
curr = curr.next;
}
ListNode head2 = curr.next;
curr.next = null;
curr = head2;
for(int i=1;i<subLength && curr!=null && curr.next!=null; i++){
curr = curr.next;
}
ListNode next = null;
if(curr != null){
next = curr.next;
curr.next = null;
}
ListNode merged = merge(head1, head2);
prev.next = merged;
while (prev.next != null){
prev = prev.next;
}
curr = next;
}
}
return dummyHead.next;
}
public ListNode merge(ListNode head1, ListNode head2){
ListNode dummyHead = new ListNode(0);
ListNode temp = dummyHead, temp1 = head1, temp2 = head2;
while (temp1!=null && temp2!=null){
if(temp1.val<=temp2.val){
temp.next=temp1;
temp1=temp1.next;
}else{
temp.next=temp2;
temp2=temp2.next;
}
temp=temp.next;
}
if(temp1 != null){
temp.next=temp1;
}else if(temp2!=null){
temp.next=temp2;
}
return dummyHead.next;
}
}