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
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"<
Link; } } //function to peek into the stack void peek(){ cout<<"\nPeeping into the stack:"<
data; } //function to check if the stack is empty void isEmpty(){ if(top==NULL){ cout<<"\nThe Stack is empty"<
data<
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"<
>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:
‹
›
Home
View web version