Viết hàm lọc danh sách liên kết để tránh trường hợp các nút trong danh sách liên kiết bị trùng info


#include <iostream>
#include <stdio.h>
#include <conio.h>
using namespace std;
struct Node{
int data;
Node *Next;
};
Node *CreateNode(int value)
{
Node *p=new Node;
p->data=value;
p->Next=NULL;
return p;
}
void AddLast(Node* &Head, Node *p) // Them nut
{
if (Head == NULL)
Head = p;
else
AddLast(Head->Next, p);
}
void NhapGT(Node* &Head, int n) //Nhap nut
{
int x;
cout<<endl;
for(int i=0;i<n;i++)
{
cout<<"Node thu "<<i<<":";
cin>>x;
cout<<endl;
AddLast(Head,CreateNode(x));
}
}
void PrintList(Node *Head) // in ra danh sach
{
if(Head!=NULL)
{
cout<<Head->data;
PrintList(Head->Next);
}
}
void RemoveSame(Node* &Head)// Loai bo nut trung nhau
{
Node *p=new Node;
Node *q=new Node;
Node *t=new Node;
p=Head;
t=NULL;
while(p!=NULL)
{
q=p;
t=q->Next;
while(t!=NULL)
{
if(t->data==p->data)
{
q->Next=t->Next;
t->Next=NULL;
delete t;
t=q->Next;
}
else
{
q=t;
t=t->Next;
}
}
p=p->Next;
}
}
int main() // Chuong trinh chinh
{
Node *Head=new Node;
Head=NULL;
int n;
cout<<"Moi nhap so phan tu:";
cin>>n;
NhapGT(Head,n);
cout<<"Ket qua day nhap vao la : ";
PrintList(Head);
cout<<endl<<"Ket qua sau khi loc ra nhung info trung nhau la: ";
RemoveSame(Head);
PrintList(Head);
getch();
}



Nhãn bài viết:
Blog, Updated at: 06:52