1stack<int> stk;
2stk.push(5);
3int ans = stk.top(5); // ans =5
4stk.pop();//removes 5
1#include <iostream>
2using namespace std;
3int stack[100], n=100, top=-1;
4void push(int val) {
5 if(top>=n-1)
6 cout<<"Stack Overflow"<<endl;
7 else {
8 top++;
9 stack[top]=val;
10 }
11}
12void pop() {
13 if(top<=-1)
14 cout<<"Stack Underflow"<<endl;
15 else {
16 cout<<"The popped element is "<< stack[top] <<endl;
17 top--;
18 }
19}
20void display() {
21 if(top>=0) {
22 cout<<"Stack elements are:";
23 for(int i=top; i>=0; i--)
24 cout<<stack[i]<<" ";
25 cout<<endl;
26 } else
27 cout<<"Stack is empty";
28}
29int main() {
30 int ch, val;
31 cout<<"1) Push in stack"<<endl;
32 cout<<"2) Pop from stack"<<endl;
33 cout<<"3) Display stack"<<endl;
34 cout<<"4) Exit"<<endl;
35 do {
36 cout<<"Enter choice: "<<endl;
37 cin>>ch;
38 switch(ch) {
39 case 1: {
40 cout<<"Enter value to be pushed:"<<endl;
41 cin>>val;
42 push(val);
43 break;
44 }
45 case 2: {
46 pop();
47 break;
48 }
49 case 3: {
50 display();
51 break;
52 }
53 case 4: {
54 cout<<"Exit"<<endl;
55 break;
56 }
57 default: {
58 cout<<"Invalid Choice"<<endl;
59 }
60 }
61 }while(ch!=4);
62 return 0;
63}
1/* Stack is a data structure that provides two O(1) time operations:
2adding an element to the top and removing an element from the top.
3It is only possible to access the top element of a stack. */
4stack<int> s;
5s.push(3);
6s.push(2);
7s.push(5);
8cout << s.top(); // 5
9s.pop();
10cout << s.top(); // 2
1// Fast DIY Stack
2template<class S, const int N> class Stack {
3private:
4 S arr[N];
5 int top_i;
6
7public:
8 Stack() : arr(), top_i(-1) {}
9 void push (S n) {
10 arr[++top_i] = n;
11 }
12 void pop() {
13 top_i--;
14 }
15 S top() {
16 return arr[top_i];
17 }
18 S bottom() {
19 return arr[0];
20 }
21 int size() {
22 return top_i+1;
23 }
24};
1#include <stdio.h>
2
3int MAXSIZE = 8;
4int stack[8];
5int top = -1;
6
7int isempty() {
8
9 if(top == -1)
10 return 1;
11 else
12 return 0;
13}
14
15int isfull() {
16
17 if(top == MAXSIZE)
18 return 1;
19 else
20 return 0;
21}
22
23int peek() {
24 return stack[top];
25}
26
27int pop() {
28 int data;
29
30 if(!isempty()) {
31 data = stack[top];
32 top = top - 1;
33 return data;
34 } else {
35 printf("Could not retrieve data, Stack is empty.\n");
36 }
37}
38
39int push(int data) {
40
41 if(!isfull()) {
42 top = top + 1;
43 stack[top] = data;
44 } else {
45 printf("Could not insert data, Stack is full.\n");
46 }
47}
48
49int main() {
50 // push items on to the stack
51 push(3);
52 push(5);
53 push(9);
54 push(1);
55 push(12);
56 push(15);
57
58 printf("Element at top of the stack: %d\n" ,peek());
59 printf("Elements: \n");
60
61 // print stack data
62 while(!isempty()) {
63 int data = pop();
64 printf("%d\n",data);
65 }
66
67 printf("Stack full: %s\n" , isfull()?"true":"false");
68 printf("Stack empty: %s\n" , isempty()?"true":"false");
69
70 return 0;
71}
1#include <bits/stdc++.h>
2
3stack<int> stk;
4stk.push(5);
5int ans = stk.top(5); // ans =5
6stk.pop();//removes 5