Created
October 29, 2016 16:57
-
-
Save achlendra/81af499c14496ae210017b3cd7132663 to your computer and use it in GitHub Desktop.
stack implementation using linked list.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
struct Node{ | |
int data; | |
Node *next; | |
}; | |
class stack{ | |
struct Node* top; | |
public: | |
stack(){ | |
top=NULL; | |
} | |
void push(){ | |
int value; | |
Node* ptr; | |
cout<<"\n Enter the no.. "; | |
cin>>value; | |
ptr=new Node; | |
ptr->data=value; | |
ptr->next=NULL; | |
if(top!=NULL) | |
ptr->next=top; | |
top=ptr; | |
} | |
void pop(){ | |
Node* temp; | |
if(top == NULL){ | |
cout<<"\n Empty stack"; | |
return; | |
} | |
temp= top; | |
top=top->next; | |
cout<<"\n popped element is "<<temp->data; | |
delete temp; | |
} | |
void printer(){ | |
Node* temp1=top; | |
cout<<"\n The stack is "; | |
while (temp1!=NULL){ | |
cout<<temp1->data<<" "; | |
temp1=temp1->next; | |
} | |
cout<<"\n"; | |
} | |
}; | |
int main() { | |
stack s; | |
int n; | |
cout<<"\n how many elements"; | |
cin>>n; | |
for(int i=0;i<n;i++) | |
s.push(); | |
s.printer(); | |
cout<<"\n how many elements to pop?"; | |
cin>>n; | |
for(int i=0;i<n;i++){ | |
s.pop(); | |
} | |
s.printer(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment