Introduction to Stacks
In the field of computer science and programming, a stack is an abstract data type that represents a collection of elements. It follows the Last-In-First-Out (LIFO) principle, meaning that the last element added to the stack is the first one to be removed.
1#include <iostream>
2using namespace std;
3
4int main() {
5 // Creating a stack using an array
6 int stack[5];
7 int top = -1;
8
9 // Push operation
10 top++;
11 stack[top] = 1;
12 top++;
13 stack[top] = 2;
14 top++;
15 stack[top] = 3;
16
17 // Pop operation
18 top--;
19
20 // Peek operation
21 cout << "Top element: " << stack[top] << endl;
22
23 return 0;
24}
Let's break down the code snippet above:
We first declare an array
stack
which will be used to store the elements of the stack.We also declare a variable
top
to keep track of the index of the top element in the stack.In the push operation, we increment
top
by 1 and assign the element to be added to the stack atstack[top]
.In the pop operation, we decrement
top
by 1 to remove the top element from the stack.In the peek operation, we simply print the top element of the stack.
Using this code snippet as an example, you can see the basic implementation of a stack using an array in C++. The principles and concepts discussed here can be applied to other programming languages as well.
Next, we will dive deeper into implementing the stack data structure and exploring its associated methods.
xxxxxxxxxx
using namespace std;
int main() {
// Creating a stack using an array
int stack[5];
int top = -1;
// Push operation
top++;
stack[top] = 1;
top++;
stack[top] = 2;
top++;
stack[top] = 3;
// Pop operation
top--;
// Peek operation
cout << "Top element: " << stack[top] << endl;
return 0;
}