Tuesday, October 16, 2012

Linked List Implementation using C++


Linked List is a sequential storage data structure. It provides a more flexible storage system. Linked List overcome the limitations of arrays. In case of array,on writing a program we had to decide the maximum amount of memory that would be needed for our arrays. If the number of element store in the array is less than the maximum size declare then left space is wasted. Linked List overcome this limitation by providing sequential storage mode. A Linked List consist of sequential node that are linked with each other. Each node in a Linked List has two parts. First part contain the data and second part contain the address of the next node.



/*Program for Implementation of Linked List using C++*/


#include<iostream.h>

#include<conio.h>
class node
{
public:
int data;
node *next;
node()
{
data=0;
next=NULL;
}
node(int x)
{
data=x;
next=NULL;
}
};
class linked_list
{
node *head;
public:
int addNodeAtFront(node *n);
int isEmpty();
node* getLastNode();
int addNodeAtEnd(node *n1);
void display();
linked_list()
{
head=NULL;
}
};
int linked_list::addNodeAtFront(node *n)
{
int i=0;
n->next=head;
head=n;
i=1;
return i;
}
int linked_list::isEmpty()
{
if(head==NULL)
return 1;
else return 0;
}
node* linked_list::getLastNode()
{
node *ptr=head;
while(ptr->next!=NULL)
ptr=ptr->next;
return ptr;
}
int linked_list::addNodeAtEnd(node *n1)
{
if(head==NULL)
head=n1;
else
{
node *n2=getLastNode();
n2->next=n1;
}
return 1;
}
void linked_list::display()
{
node *ptr=head;
if(head==NULL)
{
cout<<"List is empty";
}
while(ptr!=NULL)
  {
  cout<<"\t"<<ptr->data;
  ptr=ptr->next;
  }

}
void main()
{
int x,q,ch,num;
linked_list l;
node n1;
while(ch!=5)
{
clrscr();
cout<<"\t\t\nPlz enter your choice:\n1.Add node in front.\n2. Find last node.\n3.Add node at end.\n4.Display.\n5.Exit\n";
cin>>ch;
switch (ch)
{
case 1:cout<<"Enter number of Element you want to enter:\n";
cin>>num;
for(int i=0;i<num;i++)
{       cout<<i+1<<".Enter value\t";
cin>>x;
node *n=new node(x);
       q=l.addNodeAtFront(n);
}
       if(q==1)
{
cout<<"Inserted";

l.display();
       }
       getch();
       break;
case 2:l.getLastNode();
l.display();
getch();
break;
case 3:cout<<"Enter number of value you want to add\n";
cin>>num;
for(i=0;i<num;i++)
{
cout<<i+1<<".Enter value:\t";
cin>>x;
node *n1=new node(x);
       q=l.addNodeAtEnd(n1);
}
       if(q==1)
{
cout<<"Inserted";

l.display();
       }
       getch();
       break;
case 4:l.display();
       getch();
       break;
 }
 }
}

No comments: