Stack implementation using link list in C++
Stack implementation using link list in C++
Animated picture is here. So need to wait for some seconds to load it completely.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | // 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; } |