DSLK đơn
/*Cho tệp văn bản "daysonguyen-bai32.txt" chứa dãy số nguyên,
trên tệp không có thông tin về số phần tử của dãy số. Đọc dãy số từ tệp văn bản, lưu dãy số trong
danh sách liên kết đơn theo đúng thứ tự trên tệp. Đưa dãy số trong DSLKD ra màn hình.
Tìm xem trong dãy số có phần tử nào bằng x không. Xóa một phần tử có giá trị bằng x.
*/
include<iostream>
#include<stdio.h>
#include<fstream>
using namespace std;
class Slist
{
private:
struct node
{
int infor;
node *link;
} *F;
public:
Slist();
~Slist();
void lastInsert(int x);
bool search(int x);
void show();
bool remove(int x);
};
int main()
{
Slist S;
ifstream fin("daysonguyen-bai32.txt");
int x;
while(fin>>x)
{
S.lastInsert(x);
}
cout<<"Day so doc duoc tu tep la: ";
S.show();
cout<<"\nNhap vao so can xoa x: ";
cin>>x;
if(S.search(x))
{
cout<<"Tim thay phan tu bang x: "<<x<<"trong DSLKD";
if(S.remove(x))
{
cout<<"Da xoa phan tu "<<x<<"trong dslkd";
S.show();
}
}
else
cout<<"khong co phan tu nao = x trong DSLKD";
cout<<endl;
return 0;
}
Slist::Slist():F(NULL){}
Slist::~Slist()
{
while(F)
{
node *P = F;
F = F->link;
delete P;
}
}
void Slist::lastInsert(int x)
{
node *N = new node;
N->infor = x;
N->link = NULL;
if(F==NULL)
F=N;
else
{
node *P = F;
while(P->link)
{
P=P->link;
}
P->link = N;
}
}
bool Slist::search(int x)
{
node *M = F;
while(M)
{
if(M->infor==x) return 1;
M = M->link;
}
return 0;
}
void Slist::show()
{
node *P = F;
while(P)
{
cout<<P->infor<<" ";
P=P->link;
}
}
bool Slist::remove(int x)
{
if(F==NULL) return 0;
node *M = F, *P;
while(M)
{
if(M->infor==x) break;
else P=M; M = M->link;
}
if(M)
{
if(M==F) F=F->link;
else P->link = M->link;
delete M;
return 1;
}
return 0;
}
Last updated