Mark As Completed Discussion

The concept of a stack is similar to a stack of books or plates, where the last item placed on top is the first item to be removed. In computer science, a stack is a data structure that follows a similar last-in, first-out (LIFO) order.

Imagine you have a pile of plates, and you want to add more plates to it. You would place each new plate on top of the pile. When you want to remove a plate, you would start from the top of the pile and remove the topmost plate first.

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  // Creating a Stack
6  int stack[5];
7  int top = -1;
8
9  // Pushing elements into the stack
10  top++;
11  stack[top] = 1;
12
13  top++;
14  stack[top] = 2;
15
16  top++;
17  stack[top] = 3;
18
19  // Popping elements from the stack
20  int popped = stack[top];
21  top--;
22
23  // Accessing the top element of the stack
24  int topElement = stack[top];
25
26  // Printing the stack
27  cout << "Stack: ";
28  for (int i = 0; i <= top; i++) {
29    cout << stack[i] << " ";
30  }
31  cout << endl;
32
33  // Printing the popped and top element
34  cout << "Popped: " << popped << endl;
35  cout << "Top Element: " << topElement << endl;
36
37  return 0;
38}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment