-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked List Sorting and Printing.cpp
74 lines (63 loc) · 1.3 KB
/
Linked List Sorting and Printing.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
#include <bits/stdc++.h>
#include <cstdlib>
using namespace std;
struct tnode{
int key;
int value;
struct tnode *next;
};struct tnode *head = NULL;
void push(int key, int val){
struct tnode *newNode = (struct tnode*)malloc(sizeof(struct tnode));
(*newNode).key = key;
(*newNode).value = val;
(*newNode).next = NULL;
if(head == NULL){
head = newNode;
}
else{
struct tnode *ptr = head;
while(ptr->next != NULL)ptr=ptr->next;
ptr->next = newNode;
}
}
void bubbleSort(){
struct tnode *ptr=head;
struct tnode *ptr2;
for(int i=1; i<6 ; i++){
ptr2=head;
for(int j=0; j<i ; j++){
if(ptr->key < ptr2 -> key){
swap(ptr2 -> key, ptr -> key);
swap(ptr2 -> value, ptr -> value);
}
else if(ptr -> key == ptr2 -> key){
if(ptr -> value < ptr2 -> value){
swap(ptr2 -> key, ptr -> key);
swap(ptr2 -> value, ptr -> value);
}
}
ptr2 = ptr2 -> next;
}
ptr = ptr->next;
}
}
void print(){
struct tnode *ptr = head;
while(ptr != NULL){
cout <<"Key : " << ptr->key <<" Value : "<<ptr -> value << endl;
ptr = ptr -> next;
}
}
int main(){
int size=5, key, value;
while(size--){
cin >> key >> value;
push(key, value);
}
cout<<"List yang tidak terurut : \n";
print();
cout<<"\nList yang terurut secara Ascending : \n";
bubbleSort();
print();
return 0;
}