Stack implementation using link list in C++
Animated picture is here. So need to wait for some seconds to load it completely.
// Write a C++ program to Implement a stack with push and pop operations #include <bits/stdc++.h> using namespace std; // Declaration of node for linked list struct Node { int data; struct Node* link; }; struct Node* top; // pus at the start void push(int data) { // Creation of a new node temp and allocate memory. it will stores addresses struct Node* temp; temp = new Node(); // if stack (heap) is full, inserting an values would lead to stack overflow if (!temp) { cout << "\nstack is full/overflow"; exit(1); } // filling link list nodes with data temp->data = data; // Put top pointer reference into temp link temp->link = top; // Make temp as top of Stack top = temp; } // User define function to check if // the stack is empty or not int isEmpty() { return top == NULL; } // User define function to return top values in a stack int peek() { // Check for empty stack if (!isEmpty()) return top->data; else exit(1); } // User define function to pop top values from the stack void pop() { struct Node* temp; // Check for stack underflow if (top == NULL) { cout << "\nStack Underflow" << endl; exit(1); } else { // Top assign into temp temp = top; // Assign second node to top top = top->link; // Destroy connection between // first and second temp->link = NULL; // Release memory of top node free(temp); } } // Function to print all the // valuess of the stack void display() { struct Node* temp; // Check for stack underflow if (top == NULL) { cout << "\nStack Underflow"; exit(1); } else { temp = top; while (temp != NULL) { // Print node data cout << temp->data << "-> "; // Assign temp link to temp temp = temp->link; } } } // Driver Code int main() { // Push the valuess of stack push(44); push(55); push(62); // Display stack valuess display(); // Print top values of stack cout << "\nTop values is " << peek() << endl; // Delete top valuess of stack pop(); pop(); // Display stack valuess display(); // Print top values of stack cout << "\nTop values is " << peek() << endl; return 0; }