Data Structure Using C++
List Data Structure
List Using Array
class list
{
private:
int current;
int size;
int *ptr;
int length;
public:
list(const int l);
void start();
void next();
void back ();
void tail ();
void clear();
int getValue();
int getSize();
void add (int val);
void update(int val);
void remove();
void find(int val);
void copy(list l2);
void showList();
~list();
};
list::list(int l)
:length(l)
{
ptr=new int [length];
for(int i=0;i<length;i++)
{
ptr[i]=-1;
}
current=-1;
size=0;
}
void list::start()
{
current=0;
}
void list::next()
{
current++;
}
void list::back()
{
current--;
}
void list::tail()
{
current=size;
}
void list::clear()
{
for(int i=0;i<size;i++)
{
ptr[i]=-1;
}
size=0;
current=-1;
}
int list::getValue(){
return ptr[current];
}
int list::getSize(){
return size;
}
void list::add (int val)
{
if(size==length){
cout<<"Array is full, Can't insert!"<<endl;
}else if(current==size-1){
ptr[++current]=val;
size++;
}
else{
for(int i=size;i>current;i--)
{
ptr[i]=ptr[i-1];
}
ptr[++current]=val;
size++;
}
}
void list::update(int val){
ptr[current]=val;
}
void list::remove()
{
ptr[current--]=-1;
size--;
for(int i=++current;i<size;i++)
{
ptr[i]=ptr[i+1];
}
}
void list::find(int val)
{
int i;
for(i=0;i<size;i++)
{
if(ptr[i]==val){
break;
}
}
if(i<size){
cout<<"Value found at loc "<<++i<<endl;
}else{
cout<<"Value not found!"<<endl;
}
}
void list::copy(list l2){
if(length>=l2.getSize())
{
l2.start();
for(int i=0;i<l2.getSize();i++)
{
ptr[i]=l2.getValue();
l2.next();
}
}
}
void list::showList()
{
for(int i=0;i<size;i++)
{
cout<<ptr[i]<<" ";
}
cout<<endl;
}
list::~list(){
delete[] ptr;
}
int main ()
{
list l(10);
l.add(2);
l.add(6);
l.add(8);
l.add(7);
l.add(1);
l.showList();
l.start();
l.next();
l.next();
l.add(9);
l.showList();
l.remove();
l.update(0);
l.showList();
l.find(9);
list l2(10);
l2.add(1);
l2.add(3);
l2.add(5);
l2.copy(l);
l2.showList();
}
Let me know in the comment section if you have any question.
Previous Post:
List Data Structure Using Array In C++
Next Post:
Comments
Post a Comment