Implementation of Stack
by Linked List
Shirish Goyal
Stack is a Data Structure which allows insertion and deletion at only one end.
Implementing a Stack by A linked List requires:
A Class Stack
A Node Structure
A Node Pointer ''Top''
Constructor
Destructor
Functions:
Push Element
Pop Element
Display Stack
Count Elements
Various Control Checks must be Created at Approprite Points which prevent any exceptions
While Adding an Element , Free Space must be checked for a free node else “Stack Full” must be fired.
Similarly , while deleting Element , if there is no element left in list, ”Stack is Empty” must be displayed.
Top Node must be set to NULL by Constructor
All the Nodes of Stack must be deleted before ending the program using Destructor.
by Linked List
Shirish Goyal
Stack is a Data Structure which allows insertion and deletion at only one end.
Implementing a Stack by A linked List requires:
A Class Stack
A Node Structure
A Node Pointer ''Top''
Constructor
Destructor
Functions:
Push Element
Pop Element
Display Stack
Count Elements
Various Control Checks must be Created at Approprite Points which prevent any exceptions
While Adding an Element , Free Space must be checked for a free node else “Stack Full” must be fired.
Similarly , while deleting Element , if there is no element left in list, ”Stack is Empty” must be displayed.
Top Node must be set to NULL by Constructor
All the Nodes of Stack must be deleted before ending the program using Destructor.
| Code: |
|
Creating a Node Structure ***************************Node.h************************************ // Node Structure struct Node { int data; Node* next; }; Creating a Stack Class *****************************Stack.h****************************************** // Stack Class Structure class Stack { private: Node *top; // top pointing to Top of Stack public: //constructor Stack() { top=NULL; // for empty stack at beginning } // pushing element on stack void push(int item) { Node *temp; temp=new Node; //check for avail if (temp==NULL) { cout<<endl<<"Stack is Full"; } temp->data=item; temp->next=top; cout<<endl<<"Element Pushed in :"<<item; top=temp; } // popping out top element of stack int pop() { //check for empty stack if(top==NULL) { cout<<endl<<"Stack is Empty"; return 1; } int item; item=(top->data); //deleting top element Node* temp; temp=top; top=(top->next); delete temp; cout<<endl<<"Element Popped Out :"<<item; return item; } // display item on stack void display() { Node* ptr; ptr=top; cout<<endl<<"Contents of Stack"<<endl; while(ptr!=NULL) { cout<<(ptr->data)<<endl; ptr=ptr->next; } delete ptr; } // destructor ~Stack() { Node *temp; while(top!=NULL) { temp=top; top=top->next; delete temp; } } }; Main Program *********************************Stack.cpp************************************* #include<iostream.h> #include "Node.h" #include "Stack.h" void main() { Stack s; s.push(10); s.push(20); s.push(30); s.display(); s.pop(); s.pop(); s.pop(); s.pop(); s.display(); } |
