Wed Jan 23, 2013 3:56 pm
#include<iostream.h>
#ifndef class_H
#define class_H
typedef int ListElementType;
class List
{
public:
List();
List(ListElementType [],const int);
void insert(const ListElementType &elem);//Only insertion
void append(List &L);//append Function
List * copy();//Copy function
bool first(ListElementType &elem);
bool next(ListElementType &elem);
bool traverse(); //Traverse the list
bool before(const ListElementType );//Insert Berfore agiven element
void saveTofile();
List LoadFromfile();
private:
struct NODE;
typedef NODE* Link;
struct NODE
{
ListElementType elem;
Link next;
};
Link head;
Link current;
Link tail;
int counter;
};
#endif
#include<fstream.h>
#include"Class.h"
List::List()
{
head=0;
current=0;
tail=0;
counter=0;
}
void List::insert(const ListElementType &elem)
{
counter++;
Link addedNode=new NODE;
addedNode->elem=elem;
if(head==0)
{
head=addedNode;
}
else
tail->next=addedNode;
//
tail=addedNode;
tail->next=0;
}
bool List::first(ListElementType &elem)
{
if(head==0)
return false;
elem=head->elem;
current=head;
return true;
}
bool List::next(ListElementType &elem)
{
if(current->next==0) {return false;}
else
{
current=current->next;
elem=current->elem;
return true;
}
}
////////// ///Added Functions ////////////
bool List::traverse()
{
if(head==0)return false;
Link prev=head;
while(prev!=0)
{
cout<<prev->elem<<",";
prev=prev->next;
}
cout<<endl;
return true;
}
List::List(ListElementType a[],const int size)//Constructor that insert ARRAY in the list
{
head=0;
current=0;
tail=0;
counter=0;
for(int i=0;i<size;i++)
insert(a[i]);
}
//////// ////////////////////
void List::append(List &L)
{
tail->next=L.head ;
tail=L.tail;
}
///////////////////////////////////////////////////
List * List::copy()//copy function
{
List *L=new List;
Link prev=head;
for(prev=head;prev!=0;prev=prev->next)
{
L->insert(prev->elem);
}
return L;
}
List List::LoadFromfile()
{
List L;
ifstream in("file.txt");
ListElementType elem;
while(true)
{
in>>elem;
if(in.eof())break;
L.insert(elem);
}
return L;
}
void List::saveTofile()
{
ofstream out("file.txt");
ListElementType elem;
first(elem);
bool notEnd;
while(true)
{
out<<elem<<" ";
notEnd=next(elem);
if(!notEnd)break;
}
}
#include<iostream.h>
#include"Class.h"
void main()
{
int a[6]={4,6,3,3,10,2};
List L1 ,L2(a,6);
List *ptr;
int i;
cout<<"Enter items to add to list,add 0 to stop "<<endl;
cin>>i;
while(i!=0)
{
L1.insert(i);
cin>>i;
}
cout<<"Here are the items in the list.\n";
L1.traverse();
L1.saveTofile();
L2.traverse();
List L3=L2.LoadFromfile();
L2.append(L1);
ptr=L2.copy();
ptr->append(L2);
L2.traverse();
ptr->traverse();
L3.traverse();
}
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.