Tuần 4
#include
"ham.h"
//them mot phan tu vao dau danh sach
void
themdau(node *&phead,int x)
{
if(phead==NULL)
{
phead=new node;
phead->data=x;
phead->next=NULL;
}
else
{
node *nd;
nd=new node;
nd->data=x;
nd->next=phead;
phead=nd;
}
}
//Nhap danh sach ban dau
void
NhapDSDau(node *&phead)
{
int n,i=0,x;
node *cur;
cout<<"Nhap so phan tu:";
cin>>n;
while(i<n)
{
cout<<"Nhap phan tu thu "<<i+1<<":";
cin>>x;
if(phead==NULL)
{
phead=new node;
phead->data=x;
phead->next=NULL;
cur=phead;
}
else
{
cur->next=new node;
cur=cur->next;
cur->data=x;
cur->next=NULL;
}
i++;
}
}
//Xuat danh sach
void
xuat(node *phead)
{
node *cur;
cur=phead;
while(cur!=NULL)
{
cout<<cur->data<<" ";
cur=cur->next;
}
cout<<"
";
}
//Them mot phan tu vao cuoi danh sach
void
themcuoi(node *&phead,int x)
{
node *cur;
cur=phead;
if(phead==NULL)
{
phead=new node;
phead->data=x;
phead->next=NULL;
}
else
{
while(cur->next!=NULL)
{
cur=cur->next;
}
node *nd;
nd=new node;
nd->data=x;
nd->next=NULL;
cur->next=nd;
}
}
//Xoa cac so bang gia tri cho truoc
void
xoacacsobanggiatrichotruoc(node *&phead,int t)
{
node *cur,*team;
while(t==phead->data)
{
team=phead;
phead=phead->next;
delete(team);
}
cur=phead;
while(cur->next!=NULL)
{
if(cur->next->data==t)
{
team=cur->next;
cur->next=team->next;
delete team;
}
else
{
cur=cur->next;
}
}
}
//Dao nguoc danh sach
void
daonguocdanhsach(node *&phead)
{
int n=0;
int tmp;
node *cur;
cur=phead;
node *cur1;
cur1=phead;
while(cur!=NULL)
{
n++;
cur=cur->next;
}
cur=phead;
for(int i=0;i<n/2;i++)
{
for(int j=0;j<n-i-1;j++)
{
cur1=cur1->next;
}
tmp=cur->data;
cur->data=cur1->data;
cur1->data=tmp;
cur=cur->next;
cur1=phead;
}
}
//Tong cac gia tri cua mang
void
tongcacgiatri(node *phead,int &tong)
{
tong=0;
node *cur;
cur=phead;
while(cur!=NULL)
{
tong=tong+cur->data;
cur=cur->next;
}
}
//Tim hai so co gia tri gan nhau nhat (co the bang nhau
void
timsocogiatriganhaunhat(node *phead,int &a,int &b)
{
int n=0,min=5000;
int hieu=0;
node *cur;
node *cur1;
cur=phead;
cur1=phead;
while(cur!=NULL)
{
cur=cur->next;
n++;
}
cur=phead;
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n;j++)
{
if(cur!=cur1)
{
hieu=cur->data-cur1->data;
hieu=abs(hieu);
if(hieu<min)
{
a=cur->data;
b=cur1->data;
min=hieu;
}
}
cur1=cur1->next;
}
cur1=phead;
cur=cur->next;
}
}
Bạn đang đọc truyện trên: AzTruyen.Top