Now that we have learned about the stack data structure and its operations, let's explore some real-world applications where stacks are commonly used.
1. Function Call Stack:
In programming languages, such as C++, the function call stack is an important application of stacks. Whenever a function is called, its parameters, return address, and local variables are stored in a stack frame. The function parameters and variables are pushed onto the stack, and when the function returns, its stack frame is popped off the stack.
Here's an example in C++:
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4void functionB(int n) {
5 if (n > 0) {
6 functionA(n - 1);
7 }
8}
9
10void functionA(int n) {
11 if (n > 0) {
12 functionB(n - 1);
13 }
14}
15
16int main() {
17 functionA(5);
18 return 0;
19}
xxxxxxxxxx
using namespace std;
int main() {
// Code snippet goes here
return 0;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment