Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

/* Implementation of Stack using Linked List */

using namespace std;


#include<iostream>
template<typename T>
struct node{
T data;
struct node <T> *link;
};
template<class T>
class StackList{
private:
struct node<T> *head;
struct node<T> *top;
public:
StackList(){
head = top = NULL;
}
struct node<T> * createNode(T value){
struct node<T> *x;
x = (struct node<T> *)malloc(sizeof(struct node<T>));
x->data = value;
x->link = NULL;
return x;
}
void push(T data){
struct node<T> *x = createNode(data);
if(isEmpty()){
head = top = x;
}
else{
top->link = x;
top = x;
}
}
T peek(){
if(!isEmpty())
return top->data;
return 0;
}
int isEmpty(){
if(head == NULL)
return 1;
else
return 0;
}
void pop(){
if(!isEmpty()){
struct node <T> * x = head;
if(x->link == NULL){
cout<<x->data<<"is popped"<<endl;
free(top);
head = top = NULL;
}
while(x->link->link != NULL)
x= x->link;
cout<<x->link->data<<"is popped"<<endl;
free(top);
x->link = NULL;
top = x;
}
}
void displayStack(struct node <T> *t){
if(t!=NULL){
displayStack(t->link);
cout<<t->data<<endl;
}
}
void display(){
if(isEmpty())
cout<<"Stack is Empty"<<endl;
else
displayStack(head);
}
};

//DRIVER PROGRAM
using namespace std;
#include<iostream>
//#include "StackADT.h"
#include "StackList.h"
int main(){
int ch;
char c;
StackList <char> myStack;
while(true){
cout<<"----MENU----";
cout<<"\n1.Push\n2.Pop\n3.Peek\n4.Display\n";
cin>>ch;
switch(ch){
case 1: char x;
cout<<"Enter data "<<endl;
cin>>x;
myStack.push(x);
break;
case 2: myStack.pop();
break;
case 3: c = myStack.peek();
if(c==0)
cout<<"Stack is empty"<<endl;
else
cout<<"The top element is:"<<myStack.peek()<<endl;
break;
case 4: cout<<"The Stack is\n";
myStack.display();
break;
default: return 0;
}
}
return 0;
}

You might also like