-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAlternate-Sorted-LinkedList.java
92 lines (70 loc) · 1.79 KB
/
Alternate-Sorted-LinkedList.java
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
/*
class Node {
int data;
Node next;
public Node (int data){
this.data = data;
this.next = null;
}
}
*/
class Solution {
public Node sort(Node head){
Node head1 = new Node(-1);
Node head2 = new Node(-1);
Node ch1 = head1;
Node ch2 = head2;
Node cur = head;
while(cur != null){
ch1.next = cur;
ch1 = ch1.next;
cur = cur.next;
if(cur != null){
ch2.next = cur;
ch2 = ch2.next;
cur = cur.next;
}
ch1.next = null;
ch2.next = null;
}
head1 = head1.next;
head2 = head2.next;
head2 = reverseList(head2);
return sortedMerge(head1, head2);
}
public Node sortedMerge(Node head1, Node head2) {
Node tmp = new Node(0);
Node cur = tmp;
while(head1 != null && head2 != null){
if(head1.data < head2.data){
cur.next = head1;
head1 = head1.next;
}
else{
cur.next = head2;
head2 = head2.next;
}
cur = cur.next;
}
if(head1 != null){
cur.next = head1;
}
if(head2 != null){
cur.next = head2;
}
return tmp.next;
}
public Node reverseList(Node head){
Node prev = null;
Node cur = head;
Node next = null;
while(cur != null){
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
head = prev;
return head;
}
}