01/10/2018, 10:08
Tìm max trong danh sách liên kết đơn
mình tìm max trong danh sách liên kết đơn nhưng ko biết vì sao ko tìm dc. mong các bạn giúp đỡ!!!
#include<iostream>
using namespace std;
struct node{
int GiaTri;
struct node *next;
};
typedef struct node NODE;
struct list{
NODE *dau;
NODE *cuoi;
};
typedef struct list LIST;
NODE *KhoiTaoNODE(int x)
{
NODE *p=new NODE;
if(p==NULL)
{
cout <<"ko du vung nho cap phat";
return NULL;
}
p->GiaTri=x;
p->next=NULL;
return p;
}
void KhoiTao(LIST &l)
{
l.dau=NULL;
l.cuoi=NULL;
}
void HienThiDS(LIST l)
{
for(NODE *k=l.dau;k!=NULL;k=k->next)
{
cout << k->GiaTri << " ";
}
}
void ThemVaoDau(LIST &l,NODE *p)
{
if(l.dau==NULL)
{
l.dau=l.cuoi=p;
}
else{
p->next=l.dau;
l.dau=p;
}
}
void ThemVaoCuoi(LIST &l,NODE *p)
{
if(l.dau==NULL)
{
l.dau=l.cuoi=p;
}
else{
l.cuoi->next=p;
l.cuoi=p;
}
}
int Max(LIST l)
{
NODE *p;
int Max;
Max=l.dau->GiaTri;
while(p!=NULL)
{
if(Max < p->GiaTri)
{
Max = p->GiaTri;
}
p=p->next;
}
return Max;
}
int main()
{
LIST l;
KhoiTao(l);
int n;
cout << "nhap n: ";
cin >> n;
for (int i=1;i<=n;i++)
{
int x;
cout << "nhap x: "<< endl;
cin >> x;
NODE *p=KhoiTaoNODE(x);
ThemVaoDau(l,p);
}
cout << "danh sach la: " << endl;
HienThiDS(l);
cout << "gia tri lon nhat la: "<<Max(l);
return 0;
}
Bài liên quan
thế này mới đúng