01/10/2018, 09:54
Linked List C++. Lỗi khi insert vào vị trí K. Ai giúp với ạ
Ideone.com
Ideone is something more than a pastebin; it's an online compiler and debugging tool which allows to compile and run code online in more than 40 programming languages.
#include "iostream"
#include "string"
#include "conio.h"
#include "cstdlib"
using namespace std;
struct ThongTin
{
string name;
string address;
int old;
};
struct SinhVien
{
ThongTin imformation;
SinhVien *next;
};
typedef SinhVien* List;
void initializer(List &L)
{
L = NULL;
}
int length(List L)
{
SinhVien* Q = L;
int dem = 0;
while(Q!=NULL)
{
dem ++;
Q = Q->next;
}
return dem;
}
bool isEmpty(List L)
{
if (L == NULL)
{
return true;
} else return false;
}
void Nhap(ThongTin &Ithongtin)
{
cin.ignore();
cout<<" Nhap Ten : "; getline(cin,Ithongtin.name);
cout<<" Tuoi : "; cin>>Ithongtin.old;
cin.ignore();
cout<<" Dia Chi : "; getline(cin,Ithongtin.address);
}
SinhVien* MakeNode(SinhVien *P,ThongTin thongtin)
{
P = new SinhVien;
P->next = NULL;
P->imformation.name = thongtin.name;
P->imformation.old = thongtin.old;
P->imformation.address = thongtin.address;
return P;
}
void insertFirst(List &L)
{
SinhVien *P;
ThongTin Fthongtin;
Nhap(Fthongtin);
P = MakeNode(P,Fthongtin);
P->next = L;
L = P;
}
void insertK(List &L,int k){
if(k<1 || k > length(L)+1)
{
cout<<"Vi tri khong hop le " <<endl;
}
else if(k == 1)
{
insertFirst(L);
}
else
{
ThongTin Kthongtin;
SinhVien *Q = L;
int vitri = 0;
SinhVien*P ;
P = MakeNode(P,Kthongtin);
while(Q!= NULL && vitri != k-1)
{
vitri++;
Q = Q->next;
}
P->next = Q->next;
Q->next = P;
}
}
void Xuat(List L)
{
SinhVien *Q =L;
while(Q!=NULL){
cout<<"Name : "<<Q->imformation.name<<endl;
cout<<"Old : "<<Q->imformation.old<<endl;
cout<<"Address : "<<Q->imformation.address<<endl;
Q = Q->next;
}
}
void Menu(List L)
{
int position;
int choice;
while(1){
cout<<"1 : Nhap vao dau Danh Sach "<<endl;
cout<<"2 : Nhap vao vi tri cho truoc"<<endl;
cout<<"3 : Xuat Danh Sach "<<endl;
cout<<"4 : Check Empty List "<<endl;
cout<<"5 : Ket Thuc "<<endl;
cout<<" Ban chon so : "; cin>>choice;
switch(choice)
{
case 1:
insertFirst(L);
break;
case 2:
cout<<"Import position you need add data "; cin>>position;
cin.ignore();
insertK(L,position);
break;
case 3:
Xuat(L);
break;
case 4:
if(isEmpty(L))
cout<<"List is Empty"<<endl;
else cout<<"List is'nt Empty"<<endl;
break;
case 5:
exit(0);
default :
cout<<"Nhap so tu 1 den 4" <<endl;
break;
}
}
}
int main()
{
List L;
initializer(L);
Menu(L);
return 0;
}
Bài liên quan