-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortLL.java
More file actions
158 lines (94 loc) · 3.2 KB
/
Copy pathSortLL.java
File metadata and controls
158 lines (94 loc) · 3.2 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package linkedlist;
class DoublyLinkedListNode<T> {
T data;
DoublyLinkedListNode<T> next;
DoublyLinkedListNode<T> prev;
DoublyLinkedListNode(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
public class SortLL {
public static DoublyLinkedListNode<Integer> merge(DoublyLinkedListNode<Integer>head1,DoublyLinkedListNode<Integer>head2){
DoublyLinkedListNode<Integer> one=head1;
DoublyLinkedListNode<Integer> two=head2;
DoublyLinkedListNode<Integer> head=null;
DoublyLinkedListNode<Integer> tail=null;
if(head1==null){
return head2;
}
if(head2==null){
return head1;
}
while(one!=null && two!=null){
if(one.data<two.data){
if(head==null){
head=one;
tail=one;
one=one.next;
}
else{
tail.next=one;
one.prev=tail;
tail=tail.next;
one=one.next;
}
}
else{
if(head==null){
head=two;
tail=two;
two=two.next;
}
else{
tail.next=two;
two.prev=tail;
tail=tail.next;
two=two.next;
}
}
}
if(one!=null){
tail.next=one;
one.prev=tail;
}
if(two!=null){
tail.next=two;
two.prev=tail;
}
return head;
}
public static DoublyLinkedListNode<Integer> reverse(DoublyLinkedListNode<Integer> head){
if(head==null ||head.next==null){
return head;
}
DoublyLinkedListNode<Integer> smallans=reverse(head.next);
smallans.prev=null;
head.prev=head.next;
head.next.next=head;
head.next=null;
return smallans;
}
public static DoublyLinkedListNode<Integer> sorting(DoublyLinkedListNode<Integer> head) {
//Your Code Goes Here
if(head==null || head.next==null){
return head;
}
DoublyLinkedListNode<Integer> incstart=head.next;
// DoublyLinkedListNode<Integer> decstart=head;
while(incstart!=null && incstart.data>=incstart.prev.data){
incstart=incstart.next;
}
if(incstart==null){
return head;
}
DoublyLinkedListNode<Integer> list1=head;
DoublyLinkedListNode<Integer> list2=incstart;
list2.prev.next=null;
list2.prev=null;
DoublyLinkedListNode<Integer> revhead=reverse(list2);
DoublyLinkedListNode<Integer> ans=merge(list1,revhead);
return ans;
}
}