hi,
i created a linked list. it just adds values to the list called "source" and copies it to another list called "destination", it also deletes the values which is found in the source list and prints the source list again.
link_list.h
#ifndef LINK_LIST_H
#define LINK_LIST_H
class link_list
{
private:
class list
{
public:
int data;
list* next;
list();
list(int, list*);
~list();
};
list* top;
public:
link_list();
~link_list();
void insert_data(int);
void copy(const link_list* const);
void print() const;
int find(int);
};
#endif
link_list.cc
#include<iostream>
#include "link_list.h"
using namespace std;
link_list::link_list()
{
top=0;
}
link_list::list::list()
{
data=0;
next=0;
}
link_list::list::list(int data_temp,list* next_temp=0)
{
data=data_temp;
next=next_temp;
}
void link_list::insert_data(int value)
{
if(top==0)
top=new list(value);
else
{
list *temp=top;
while(!temp->next==0)
{
temp=temp->next;
}
temp->next=new list(value);
}
}
void link_list::copy(const link_list* const source_temp)
{
list* src_temp=source_temp->top;
while(src_temp!=0)
{
if(this->top==0)
{
this->top=new list(src_temp->data);
}
else
{
list *dst_temp=this->top;
while(!dst_temp->next==0)
{
dst_temp=dst_temp->next;
}
dst_temp->next=new list(src_temp->data);
}
src_temp=src_temp->next;
}
}
void link_list::print() const
{
list* temp=this->top;
while(temp!=0)
{
cout<<temp->data<<endl;
temp=temp->next;
}
}
int link_list::find(int value)
{
list* temp=this->top;
if(this->top==0)
{
cout<<"the list is empty"<<endl;
return 0;
}
while(temp!=0 && temp->data!=value)
{
temp=temp->next;
}
if(temp==0)
{
cout<<"the value does not exist"<<endl;
return 0;
}
cout<<"the value exists"<<endl;
list* prev=this->top;
if(prev==temp)
{
this->top=temp->next;
temp->next=0;
delete temp;
}
else
{
while(prev->next!=temp)
{
prev=prev->next;
}
prev->next=temp->next;
temp->next=0;
delete temp;
}
}
link_list::~link_list()
{
delete top;
}
link_list::list::~list()
{
delete next;
}
link_list_main.cc
#include<iostream>
#include "link_list.h"
using namespace std;
int main()
{
link_list source;
link_list dest;
int data;
cout<<"enter the data"<<endl;
while(cin>>data)
{
source.insert_data(data);
}
if(cin.eof())
{
cout<<"eof"<<endl;
cin.ignore(256,'\n');
cin.clear();
}
cout<<"the source list"<<endl;
source.print();
cout<<"coying to destination list"<<endl;
dest.copy(&source);
cout<<"the destination list"<<endl;
dest.print();
cout<<"enter the values to be deleted from the source list"<<endl;
while(cin>>data)
{
source.find(data);
}
cout<<"the source list"<<endl;
source.print();
}
My code works fine. i just want to know if there is any improvements i can make in my code or simplify my code..
and is my code correct?
and i am very much worried about my destructors.. are they deleting the objects which are dynamically allocated..?? is there any way i can check it?