Blogs on Computer Science
Understand and Relearn the Science
Sunday, September 20, 2015
Stack Implementation Using Linked list
Implementation of a stack using linked list is dynamic and flexible. Yet the space consumed is high and adding or manipulating the linked list is complex.
Refer to the code for more details. The Code language is C++.
Code:
//Implementation of a stack using a Singly Linked List #include<iostream> using namespace std; class stack{ public: struct Node{ int data; struct Node* Link; }; struct Node* top=NULL;//initially my stack is empty void push(){ int x; struct Node* temp=new Node(); cout<<"\nEnter the data: "; cin>>x; temp->data=x; temp->Link=top; top=temp; } void pop(){ if(top==NULL){ cout<<"\nStack underflow"<<endl; }else{ top=top->Link; } } //function to peek into the stack void peek(){ cout<<"\nPeeping into the stack:"<<endl; cout<<top->data; } //function to check if the stack is empty void isEmpty(){ if(top==NULL){ cout<<"\nThe Stack is empty"<<endl; }else{ cout<<"\nThe stack is not empty"<<endl; } } //function to print the elements of the stack void print(){ Node* temp=new Node(); temp=top; cout<<"Printing Elements in a stack"<<endl; while(temp!=NULL){ cout<<temp->data<<endl; temp=temp->Link; } } void sizeofstack(){ Node* temp=new Node(); temp=top; int sizeoftemp; while(temp!=NULL){ temp=temp->Link; sizeoftemp+=sizeof(temp); } cout<<"\nSize of the stack"<<sizeoftemp<<endl; } //function to choose the stack operations void option(){ int x=1; int options; while(x!=0){ cout<<"\nStack operations:"<<endl; cout<<"1.Push"<<endl; cout<<"2.Pop"<<endl; cout<<"3.Peek"<<endl; cout<<"4.Is Empty?"<<endl; cout<<"5.Print Stack"<<endl; cout<<"6.Stack Size"<<endl; cout<<"7.Exit"<<endl; cout<<"Enter option"<<endl; cin>>options; switch(options){ case 1: push(); break; case 2: pop(); break; case 3: peek(); break; case 4: isEmpty(); break; case 5: print(); break; case 6: sizeofstack(); break; case 7: exit(0); break; } } } }; int main(){ stack k; k.option(); }
Output:
Newer Post
Older Post
Home
About Me
Sourab
View my complete profile