Skip to content

Instantly share code, notes, and snippets.

@duyet
Created June 16, 2014 04:26
Show Gist options
  • Select an option

  • Save duyet/abd5417893f9c2db6461 to your computer and use it in GitHub Desktop.

Select an option

Save duyet/abd5417893f9c2db6461 to your computer and use it in GitHub Desktop.
# include<iostream>
using namespace std;
struct data
{
int so;
};
struct node
{
data info;
node*pnext;
};
struct list
{
node*phead;
node*ptail;
};
void init(list &l)
{
l.phead=l.ptail=NULL;
}
node*getnode(data x)
{
node*p;
p=new node;
if(p==NULL)
{
cout<<"k du bo nho";
return NULL;
}
p->info=x;
p->pnext=NULL;
return p;
}
void addfirst(list &l,node*p)
{
if(l.phead==NULL)
{
l.phead=l.ptail=p;
}
else
{
p->pnext=l.phead;
l.phead=p;
}
}
void addtail(list &l,node*p)
{
if(l.phead==NULL)
{
l.phead=l.ptail=p;
}
else
{
l.ptail->pnext=p;
l.ptail=p;
}
}
void input(list &l)
{
while(1)
{
data x;
cout<<"nhap so vao: ";
cin>>x.so;
if(x.so<=0)break;
addfirst(l,getnode(x));
}
}
void output(list &l)
{
node*p=l.phead;
while(p!=NULL)
{
cout<<"so la: "<<p->info.so<<endl;
p=p->pnext;
}
}
int total(list l)
{
node*p=l.phead;
int s=0;
while(p!=NULL)
{
s=s+p->info.so;
p=p->pnext;
}
return s;
}
int search_max(list l)
{
node*p,*max;
p=l.phead;
max=p;
while(p!=l.ptail)
{
if(p->pnext->info.so>max->info.so)
{
max=p->pnext;
}
p=p->pnext;
}
return max->info.so;
}
void listselectionsort(list &l)
{
node*p,*q,*min;
p=l.phead;
while(p!=l.ptail)
{
min=p;
q=p->pnext;
while(q!=NULL)
{
if(q->info.so<min->info.so)
{
min=q;
}
q=q->pnext;
}
int tmp=min->info.so;
min->info.so=p->info.so;
p->info.so=tmp;
p=p->pnext;
}
}
void main()
{
list l;
init(l);
input(l);
output(l);
cout<<"tong cac so la: "<<total(l);
cout<<endl;
listselectionsort(l);
output(l);
cout<<"so co gia tri lon nhat la: "<<search_max(l);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment