0% found this document useful (0 votes)
62 views8 pages

Stacks in C++

A stack is a LIFO data structure where the last element added is the first to be removed, implemented in C++ using `std::stack` or custom methods like arrays and linked lists. Basic operations include push, pop, peek, and checking if the stack is empty. Stacks are commonly used in applications such as expression evaluation, undo operations, and managing function calls.

Uploaded by

yewaleanuj01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views8 pages

Stacks in C++

A stack is a LIFO data structure where the last element added is the first to be removed, implemented in C++ using `std::stack` or custom methods like arrays and linked lists. Basic operations include push, pop, peek, and checking if the stack is empty. Stacks are commonly used in applications such as expression evaluation, undo operations, and managing function calls.

Uploaded by

yewaleanuj01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Stacks in C++

stacks explain in c++

Stacks in C++

A stack is a data structure that follows the LIFO (Last In, First Out) principle, where the last element
added to the stack is the first one to be removed. Think of a stack as a pile of plates; the last plate you
place on top is the first one you take off.
In C++, stacks can be implemented using:

1. The `std::stack` container (from the Standard Template Library - STL).


2. Custom implementation using arrays or linked lists.

1. Using `std::stack`

The `std::stack` container is easy to use and provides built-in functionality for stack operations. It
requires the `<stack>` header file.

Operations:

`push(x)` - Adds an element `x` to the top of the stack.


`pop()` - Removes the top element.
`top()` - Returns the top element.
`empty()` - Checks if the stack is empty.
`size()` - Returns the number of elements in the stack.

Example:

cpp

#include <iostream>
#include <stack>

int main() {
std::stack<int> s;

// Pushing elements onto the stack


s.push(10);
s.push(20);
s.push(30);

std::cout << "Top element: " << s.top() << std::endl; // Output: 30

// Popping elements
s.pop();
std::cout << "Top element after pop: " << s.top() << std::endl; // Output: 20

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/8
// Checking if the stack is empty
if (s.empty()) {
std::cout << "Stack is empty" << std::endl;
} else {
std::cout << "Stack size: " << s.size() << std::endl; // Output: 2
}

return 0;
}

2. Custom Implementation of a Stack

You can implement a stack using an array or a linked list to better understand its working.

Array-based Stack:

cpp

#include <iostream>
#define MAX 1000

class Stack {
int top;
int arr[MAX];

public:
Stack() { top = -1; }

// Push an element onto the stack


bool push(int x) {
if (top >= MAX - 1) {
std::cout << "Stack Overflow\n";
return false;
} else {
arr[++top] = x;
return true;
}
}

// Pop an element from the stack


int pop() {
if (top < 0) {
std::cout << "Stack Underflow\n";
return -1;
} else {
return arr[top--];
}
}

// Peek the top element


int peek() {
if (top < 0) {
std::cout << "Stack is Empty\n";
return -1;
} else {
return arr[top];
}
}

// Check if the stack is empty


bool isEmpty() {
return (top < 0);
}
};

int main() {
Stack s;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/8
s.push(10);
s.push(20);
s.push(30);

std::cout << "Top element: " << s.peek() << std::endl;

std::cout << "Popped element: " << s.pop() << std::endl;


std::cout << "Top element after pop: " << s.peek() << std::endl;

return 0;
}

Linked List-based Stack:

cpp

#include <iostream>

class Node {
public:
int data;
Node* next;

Node(int val) {
data = val;
next = nullptr;
}
};

class Stack {
Node* top;

public:
Stack() { top = nullptr; }

// Push an element onto the stack


void push(int x) {
Node* newNode = new Node(x);
newNode->next = top;
top = newNode;
}

// Pop an element from the stack


int pop() {
if (!top) {
std::cout << "Stack Underflow\n";
return -1;
}
Node* temp = top;
top = top->next;
int popped = temp->data;
delete temp;
return popped;
}

// Peek the top element


int peek() {
if (!top) {
std::cout << "Stack is Empty\n";
return -1;
}
return top->data;
}

// Check if the stack is empty


bool isEmpty() {
return top == nullptr;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/8
}
};

int main() {
Stack s;

s.push(10);
s.push(20);
s.push(30);

std::cout << "Top element: " << s.peek() << std::endl;

std::cout << "Popped element: " << s.pop() << std::endl;


std::cout << "Top element after pop: " << s.peek() << std::endl;

return 0;
}

Key Points:

1. Use `std::stack` for simpler implementation and STL features.


2. Implement a custom stack for learning or when additional control is needed.
3. Stacks are widely used in problems like expression evaluation, backtracking, and undo
operations in applications.

explain deeply

Deep Explanation of Stacks in C++

A stack is a linear data structure that works on the LIFO (Last In, First Out) principle. It allows elements
to be added and removed only at one end, called the top of the stack. This ensures that the last element
inserted is the first one removed.

Think of a real-life example: a stack of plates or books. You can only add a plate or book to the top, and
you can only remove the topmost one.

Basic Stack Operations

1. Push: Add an element to the top of the stack.


2. Pop: Remove the element from the top of the stack.
3. Peek/Top: View the top element without removing it.
4. IsEmpty: Check if the stack is empty.
5. Size: Get the number of elements in the stack.

Using STL (`std::stack`)

The C++ Standard Template Library (STL) provides a ready-to-use stack container. It simplifies stack
operations without the need to write custom implementations.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/8
Syntax:

cpp

#include <stack>
std::stack<int> s;

Operations:

`s.push(x)`: Push `x` onto the stack.


`s.pop()`: Remove the top element.
`s.top()`: Access the top element.
`s.empty()`: Returns `true` if the stack is empty.
`s.size()`: Returns the number of elements.

Example:

cpp

#include <iostream>
#include <stack>

int main() {
std::stack<int> s;

s.push(10); // Add 10 to the stack


s.push(20); // Add 20
s.push(30); // Add 30

std::cout << "Top element: " << s.top() << std::endl; // 30

s.pop(); // Remove 30
std::cout << "Top element after pop: " << s.top() << std::endl; // 20

std::cout << "Stack size: " << s.size() << std::endl; // 2

std::cout << "Is stack empty? " << (s.empty() ? "Yes" : "No") << std::endl;

return 0;
}

Custom Implementation of Stack

1. Using Arrays

An array-based implementation uses a fixed-size array and a pointer/index (`top`) to track the last
element.

Key Points:

Advantages: Simple, fast.


Disadvantages: Limited by the array size, resizing is not dynamic.

Implementation:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/8
cpp

#include <iostream>
#define MAX 1000 // Maximum stack size

class Stack {
int top; // Index of the top element
int arr[MAX]; // Array to store stack elements

public:
Stack() { top = -1; } // Initialize stack as empty

// Push operation
bool push(int x) {
if (top >= MAX - 1) { // Stack overflow check
std::cout << "Stack Overflow\n";
return false;
}
arr[++top] = x; // Increment top and add element
return true;
}

// Pop operation
int pop() {
if (top < 0) { // Stack underflow check
std::cout << "Stack Underflow\n";
return -1;
}
return arr[top--]; // Return top element and decrement
}

// Peek operation
int peek() {
if (top < 0) {
std::cout << "Stack is Empty\n";
return -1;
}
return arr[top];
}

// Check if stack is empty


bool isEmpty() {
return (top < 0);
}
};

int main() {
Stack s;

s.push(10);
s.push(20);
s.push(30);

std::cout << "Top element: " << s.peek() << std::endl; // 30

s.pop(); // Remove top element


std::cout << "Top element after pop: " << s.peek() << std::endl; // 20

return 0;
}

2. Using Linked List

A linked list implementation of a stack allows dynamic resizing. Each node contains data and a pointer to
the next node.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/8
Key Points:

Advantages: Dynamic size, no overflow unless memory is full.


Disadvantages: Slightly slower due to pointer operations, uses extra memory for pointers.

Implementation:

cpp

#include <iostream>

// Node class
class Node {
public:
int data;
Node* next;

Node(int val) {
data = val;
next = nullptr;
}
};

// Stack class
class Stack {
Node* top; // Pointer to the top element

public:
Stack() { top = nullptr; } // Initialize as empty

// Push operation
void push(int x) {
Node* newNode = new Node(x);
newNode->next = top;
top = newNode;
}

// Pop operation
int pop() {
if (!top) { // Check for underflow
std::cout << "Stack Underflow\n";
return -1;
}
Node* temp = top;
top = top->next;
int popped = temp->data;
delete temp;
return popped;
}

// Peek operation
int peek() {
if (!top) {
std::cout << "Stack is Empty\n";
return -1;
}
return top->data;
}

// Check if stack is empty


bool isEmpty() {
return top == nullptr;
}
};

int main() {
Stack s;

s.push(10);
s.push(20);
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/8
s.push(30);

std::cout << "Top element: " << s.peek() << std::endl; // 30

s.pop(); // Remove top element


std::cout << "Top element after pop: " << s.peek() << std::endl; // 20

return 0;
}

Applications of Stacks

1. Expression Evaluation:
Used for evaluating postfix and prefix expressions.
Helps in converting infix to postfix/prefix.
2. Undo Operations:
Used in text editors for "undo" functionality.
3. Backtracking:
Algorithms like maze solving and N-Queens use stacks.
4. Function Call Stack:
Manages function calls and local variables in programming languages.
5. Browser History:
Maintains back/forward navigation using stacks.

Memory and Performance

Implementation Time Complexity (Push/Pop) Space Complexity

Array O(1) O(n)


Linked List O(1) O(n) (extra space for pointers)

Let me know if you'd like a deeper dive into a specific area like applications, performance, or variations!
Is this conversation helpful so far?

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/8

You might also like