Mark As Completed Discussion

Implementing a Stack

To implement a stack data structure, we can use a linked list where each element of the stack is represented by a node in the linked list. The top of the stack will be represented by the first node in the linked list.

Let's take a look at the C++ implementation of a stack using a linked list:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4// Node class to represent individual elements in the stack
5class Node {
6public:
7  int data;
8  Node* next;
9};
10
11// Stack class
12class Stack {
13private:
14  Node* top;
15public:
16  // Constructor
17  Stack() {
18    top = nullptr;
19  }
20
21  // Push operation
22  void push(int element) {
23    Node* newNode = new Node;
24    newNode->data = element;
25    newNode->next = top;
26    top = newNode;
27  }
28
29  // Pop operation
30  int pop() {
31    if (isEmpty()) {
32      cout << "Stack is empty" << endl;
33      return -1;
34    }
35    int element = top->data;
36    Node* temp = top;
37    top = top->next;
38    delete temp;
39    return element;
40  }
41
42  // Peek operation
43  int peek() {
44    if (isEmpty()) {
45      cout << "Stack is empty" << endl;
46      return -1;
47    }
48    return top->data;
49  }
50
51  // Check if the stack is empty
52  bool isEmpty() {
53    return top == nullptr;
54  }
55};
56
57int main() {
58  // Creating a stack
59  Stack stack;
60
61  // Pushing elements
62  stack.push(1);
63  stack.push(2);
64  stack.push(3);
65
66  // Popping elements
67  cout << stack.pop() << endl; // Output: 3
68  cout << stack.pop() << endl; // Output: 2
69
70  // Peeking element
71  cout << stack.peek() << endl; // Output: 1
72
73  // Checking if the stack is empty
74  cout << stack.isEmpty() << endl; // Output: 0
75
76  return 0;
77}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment