Created
November 17, 2020 06:09
-
-
Save apshada/fb5d24eddea9a3066529e5df32db58ae to your computer and use it in GitHub Desktop.
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<bits/stdc++.h> | |
using namespace std; | |
//create a structure for Node which will | |
// contain data and pointer to next Node | |
struct Node{ | |
int data; | |
struct Node* next; | |
//Function to create new node | |
//with Next Pointing to NULL | |
Node(int x){ | |
data = x; | |
next = NULL; | |
} | |
}; | |
//Create a NULL Node which will be assign as Top | |
//of the Stack | |
Node* top; | |
//Similar to inserting at head of Linked List | |
void push(int data){ | |
//create a temp. node which | |
Node* t = new Node(data); | |
if(t == NULL){ | |
cout<<"Stack OverFlow"; | |
} | |
//temp. next is assign to top | |
t->next = top; | |
top = t; | |
} | |
//Function to display Stack | |
void display(){ | |
//Pass the Top to traverse | |
//Stack from Top to Bottom | |
Node* trav = top; | |
//Iterate until we reach NULL/End of Stack | |
while(trav != NULL){ | |
cout<<trav->data<<" "; | |
trav = trav->next; | |
} | |
} | |
int pop(){ | |
//Check if Stack is Empty or Not | |
if(top == NULL){ | |
cout<<"Stack is Empty"; | |
} | |
/* If stack is not empty then | |
assign top's data to x | |
create a temp node assign it top | |
move top forward and delete t | |
*/ | |
else{ | |
int x = top->data; | |
Node* t = top; | |
top = top->next; | |
delete t; | |
return x; | |
} | |
} | |
int main(){ | |
push(10); | |
push(20); | |
cout<<"Deleted Element is"<<pop()<<endl; | |
display(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment