SORTING A LINKED LIST
/*******************
linked list
bubble sort
complexity:O(n^2)
*******************/
#include <bits/stdc++.h>
using namespace std;
class linked_list
{
public:
int data;
class linked_list *next;
};
typedef linked_list node;
void show(node *p){
while(p){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
return;
}
void sort(node *p)
{
while(p->next){
node *test=p->next;
while(test){
if(test->data<p->data)
swap(test->data,p->data);
test=test->next;
}
p=p->next;
}
}
void create(node *p){
char c;
scanf("%d%c", &p->data, &c);
if(c=='\n')
p->next=NULL;
else
{
p->next=new node;
create(p->next);
}
return;
}
int main(){
bool x;
while(cin>>x){
node *head;
head=new node;
create(head);
cout<<"list before sorting\n";
show(head);
sort(head);
cout<<"list after sorting\n";
show(head);
}
return 0;
}
linked list
bubble sort
complexity:O(n^2)
*******************/
#include <bits/stdc++.h>
using namespace std;
class linked_list
{
public:
int data;
class linked_list *next;
};
typedef linked_list node;
void show(node *p){
while(p){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
return;
}
void sort(node *p)
{
while(p->next){
node *test=p->next;
while(test){
if(test->data<p->data)
swap(test->data,p->data);
test=test->next;
}
p=p->next;
}
}
void create(node *p){
char c;
scanf("%d%c", &p->data, &c);
if(c=='\n')
p->next=NULL;
else
{
p->next=new node;
create(p->next);
}
return;
}
int main(){
bool x;
while(cin>>x){
node *head;
head=new node;
create(head);
cout<<"list before sorting\n";
show(head);
sort(head);
cout<<"list after sorting\n";
show(head);
}
return 0;
}
No comments:
Post a Comment