Linked List as Stack
Linked Lists are a dynamic way to store data. In this program linked list is implemented as a stack i.e. the last one enterd is removed first.
/* implementing linked list as a stack*/
#include<conio.h>
#include<stdio.h>
#include<iostream.h>
struct node
{
int value;
struct node *next;
};
class linkedlist
{
public:
struct node *start;
public:
linkedlist()
{
start=NULL;
}
void insert(int a);
int remove();
void display();
};
void linkedlist::insert(int a)
{
struct node *temp;
temp = new(node);
temp->value=a;
if(start==NULL)
{
temp->next=NULL;
}
else
{
temp->next=start;
}
start=temp;
}
int linkedlist::remove()
{
struct node *temp;
int x;
temp=start;
if(start==NULL)
{
cout<<"list is empty";
}
else
{
x=temp->value;
start=temp->next;
delete(temp);
}
return x;
}
void linkedlist::display()
{
struct node *temp;
for(temp=start;temp!=NULL;temp=temp->next)
{
cout<<temp->value<<"\n";
}
}
void main()
{
clrscr();
int x;
linkedlist list;
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
x=list.remove();
cout<<"this value has been poped"<<x;
list.display();
getch();
}
Download Program


