Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- struct Stack
- {
- int data;
- Stack *next;
- };
- Stack *top = NULL;
- Stack *StackNode(int val)
- {
- Stack *newNode = new Stack();
- newNode->data = val;
- newNode->next = NULL;
- return newNode;
- }
- bool isEmpty()
- {
- if(top == NULL) return true;
- return false;
- }
- void push(int val)
- {
- Stack *newNode = StackNode(val);
- if(isEmpty()) top = newNode;
- else
- {
- newNode->next = top;
- top = newNode;
- }
- }
- void pop()
- {
- if(isEmpty()) cout<<"Can't pop from an empty stack\n";
- else
- {
- Stack *cur = top;
- top = top->next;
- free(cur);
- }
- }
- int Top()
- {
- if(isEmpty()) cout<<"Stack is empty!\n";
- else
- {
- return top->data;
- }
- }
- void printStack()
- {
- if(isEmpty()) cout<<"Stack is empty!\n";
- else
- {
- while(top != NULL)
- {
- cout<<Top()<<" ";
- pop();
- }
- }
- cout<<endl;
- }
- int main()
- {
- cout<<"Enter the number of elements: ";
- int n;
- cin>>n;
- for(int i=0; i<n; i++)
- {
- int val;
- cin>>val;
- push(val);
- }
- pop();
- printStack();
- int t;
- if(!isEmpty())
- {
- t = Top();
- cout<<t;
- }
- }
Add Comment
Please, Sign In to add comment