1. Write a program to perform the following operations on a stack.(using Linked List)a. PUSHb. POPc. ISEMPTYd. ISFULLe. PEEP
#include<iostream.h> #include<conio.h> #include<stdlib.h> class node { int data; //data part of node node *link; // link part points to next node public: node() // constructor that set NULL to link { link = NULL; } //below are functions to get/set the private members int getData() { return data; } void setData(int d) { data = d; } node* getLink() { return link; } void setLink(node *nnode) { link = nnode; } }; // stack class class StackLL { node *top; public: StackLL()// set top to NULL { top = NULL; } void push(int); void pop(); void peep(); int isEmpty(); void display(); }; //member function's body void StackLL :: push(int element) { node *nnode; nnode = new node; nnode->setData(element); if(isEmpty()) { top = nnode; } else { nnode->setLink(top); top=nnode; } } int StackLL :: isEmpty() { if(top == NULL) return 1; else return 0; } void StackLL :: pop() { node *ptr; if(isEmpty()) { cout<<endl<<"Stack Underflow"; } else { ptr = top; top = top->getLink(); delete(ptr); } } void StackLL :: display() { node *ptr; cout<<endl<<"\t\t\t"; for(ptr = top; ptr!=NULL; ptr=ptr->getLink()) { cout<<ptr->getData()<<endl<<endl<<"\t\t\t"; } } void main() { int element, ch; clrscr(); cout<<endl<<"\tStack Operation using LinkedList"; StackLL stk; while(1) { cout<<endl<<" 1. Insert"; cout<<endl<<" 2. delete"; cout<<endl<<" 3. Exit"<<endl; cin>>ch; clrscr(); cout<<endl<<"\t\t\tStack Operation using LinkedList"<<endl; switch(ch) { case 1: cout<<endl<<"Enter data: "; cin>>element; stk.push(element); stk.display(); break; case 2: stk.pop(); stk.display(); break; case 3: exit(0); default: cout<<endl<<"wrong choice"<<endl; } } getch(); } |
0 comments :