-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked list that is sorted alternatingly
135 lines (105 loc) · 2.69 KB
/
Linked list that is sorted alternatingly
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
package gfg;
//Linked list that is sorted alternatingly
import java.io.*;
import java.util.*;
class Node {
int data;
Node next;
public Node (int data) {
this.data = data;
this.next = null;
}
}
class GFG {
static void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0) {
int n = sc.nextInt();
Node head = new Node(sc.nextInt());
Node tail = head;
for(int i = 1; i < n; i++){
tail.next = new Node(sc.nextInt());
tail = tail.next;
}
Solution obj = new Solution();
head = obj.sort(head);
printList(head);
}
}
}
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(0), head2 = new Node(0);
Node temp1 = head1, temp2 = head2, temp = head;
boolean indication = true;
while(temp != null){
if(indication) {
temp1.next = temp;
temp1 = temp1.next;
}
else {
temp2.next = temp;
temp2 = temp2.next;
}
temp=temp.next;
indication=!indication;
}
temp1.next = null;
temp2.next = null;
Node curr = head2, prev=null, nxt = head2.next;
while(curr != null) {
nxt = curr.next;
curr.next = prev;
prev = curr;
curr = nxt;
}
temp = prev;
while(prev != null) {
if(prev.next == head2) {
prev.next = null;
}
prev = prev.next;
}
Node ans = new Node(0);
head2 = ans;
head1 = head1.next;
while(head1 != null && temp != null) {
if(head1.data <= temp.data) {
ans.next = head1;
head1 = head1.next;
}
else {
ans.next = temp;
temp = temp.next;
}
ans = ans.next;
}
while(head1 != null) {
ans.next = head1;
head1 = head1.next;
ans = ans.next;
}
while(temp != null) {
ans.next = temp;
temp = temp.next;
ans = ans.next;
}
return head2.next;
}
}