forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SortLinkedListAlternately.cpp
125 lines (116 loc) · 2.34 KB
/
SortLinkedListAlternately.cpp
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
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next;
Node(int x){
data =x;
next = NULL;
}
};
void sort(Node **head);
void append(struct Node** headRef, struct Node** tailRef, int newData)
{
struct Node* new_node = new Node(newData);
struct Node *last = *headRef;
if (*headRef == NULL)
{
*headRef = new_node;
*tailRef = *headRef;
return;
}
(*tailRef) -> next = new_node;
*tailRef = (*tailRef) -> next;
}
void printList(Node *head)
{
while (head != NULL)
{
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
int main()
{
int test;
cin>>test;
while(test--)
{
struct Node* head = NULL;
struct Node* tail = NULL;
int n, k;
cin>>n;
for(int i=0; i<n ;i++){
cin>>k;
append(&head, &tail, k);
}
sort(&head);
printList(head);
}
return 0;
}
void sort(Node **head)
{
Node* node = new Node(0);
Node* ptr = *head;
if(ptr->next == NULL)return;
Node* p = node;
while(ptr->next != NULL){
p->next = ptr->next;
if(ptr->next->next == NULL){
ptr->next = NULL;
p = p->next;
break;
}
ptr->next = ptr->next->next;
p = p->next;
p->next =NULL;
ptr=ptr->next;
}
p = node;
node= node->next;
while(true){
if(node->next->next == NULL){
node->next->next = p->next;
p->next = node->next;
node->next = NULL;
break;
}
Node* temp = node->next->next;
node->next->next = p->next;
p->next = node->next;
node->next = temp;
}
node = p->next;
delete p;
Node *fir = *head;
Node *sec = node;
Node *space = new Node(0);
Node *temp = space;
while(true){
if(fir == NULL){
temp->next = sec;
break;
}
else if(sec == NULL){
temp->next = fir;
break;
}
else if(fir->data <= sec->data){
temp->next = fir;
fir = fir->next;
temp = temp->next;
}
else if(fir->data > sec->data){
temp->next = sec;
sec= sec->next;
temp = temp->next;
}
}
ptr = space;
space = space->next;
*head = space;
delete ptr;
}