forked from k-samarth/Data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortLinkedList_n2.cpp
More file actions
76 lines (69 loc) · 1.42 KB
/
Copy pathSortLinkedList_n2.cpp
File metadata and controls
76 lines (69 loc) · 1.42 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
//Program to sort the LinkedList in O(n2);
#include <iostream>
using namespace std;
struct node{
int data;
node* link;
};
void InsertEnd(node** head){
node* temp = new node;
node* temp1 =*head;
int value;
cout<<"Enter the value ";
cin>>value;
temp->data=value;
if(*head==NULL)
{
temp->link=NULL;
*head=temp;
return;
}
while(temp1->link!=NULL){
temp1=temp1->link;
}
temp->link=NULL;
temp1->link=temp;
}
void Sort(node** head){
node* front=*head;
node* back=*head;
while(back!=NULL){
front =back->link;
while(front!=NULL){
if(back->data>front->data){
swap(back->data,front->data);
}
front=front->link;
}
back=back->link;
}
}
void Display(node* head){
node* temp=head;
while(temp!=NULL){
cout<<temp->data<<" ";
temp=temp->link;
}
cout<<endl;
}
int main()
{
node* head=NULL;
while(1){
int choice;
cout<<"Choose 1 for adding element and 2 for sorting"<<endl;
cin>>choice;
switch(choice){
case 1:InsertEnd(&head);
break;
case 2:Sort(&head);
break;
case 3:Display(head);
break;
case 4:return 0;
break;
default:cout<<"Invalid option"<<endl;
}
}
return 0;
}