Explaination: Here we are using classes to make linked list data structure. We first create a linked list and with the methods (push,disp,del). In this case we are only using one pointer “head” that tracks the first node of the linked list. Every time a node has to be added, its added in the front of the list and if a node has to be deleted, again first node is deleted as Stack is LIFO (Last in First Out).
To display, we simple traverse through the list and display the element.
#include<iostream.h>
#include<conio.h>
class stack{
int data;
public:
stack * next;
void push(stack ** front,int key);
void disp(stack ** front);
void del(stack ** front);
};
void stack::push(stack ** front,int key){
stack * nod;
nod = new stack;
nod->data = key;
if(front==NULL){
*front=nod;
}
else{
nod->next=*front;
*front=nod;
}
cout<<key<<" pushed \n";
}
void stack::disp(stack ** front){
stack * temp;
temp = new stack;
temp=*front;
if(temp==NULL){
cout<<"Stack Empty \n";
}
else{
while(temp->next!= NULL){
cout<<temp->data<<"----";
temp = temp->next;
}
}
}
void stack::del(stack ** front){
stack * temp;
temp = new stack;
temp=*front;
cout<<temp->data<<" deleted from the stack \n";
*front = temp->next;
}
int main(){
int n;
stack * newNode = new stack;
stack * head = NULL;
do{
cout<<"1: ADD \n";
cout<<"2: See all\n";
cout<<"3: Pop \n";
cout<<"Enter Your choice: ";
cin>>n;
switch(n){
case 1:
int dat;
cout<<"Enter the number that you want to add: ";
cin>>dat;
newNode->push(&head,dat);
break;
case 2:
newNode->disp(&head);
break;
case 3:
newNode->del(&head);
break;
default:
break;
}
}while(n<=3);
getch();
return 0;
}
Try to make Queue (FIFO: First in First Out) using similar code, but make sure that you track both first and last element in that case, as the element to be added will be at the starting of the queue and deletion will be at the end of the Queue. If you only maintain one pointer then unnecessarily you would have to traverse the whole list every time.
November 3, 2010 at 8:36 pm
Thanks for providing the source code for creating a dynamic stack for each new push, very helpful! Thanks!