Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Stack implementation using Linked Lists
- #include <iostream>
- using namespace std;
- struct node {
- int data;
- struct node *link;
- };
- struct node *top = NULL, *temp;
- int main() {
- int choice, data;
- // infinite loop is used to insert/delete infinite number of nodes
- while(true) {
- cout << "\n1. Push\n2. Pop\n3. Display\n4. Exit\n";
- cout << "\nEnter ur choice: ";
- cin >> choice;
- switch(choice) {
- case 1: // push - add an item to the stack
- temp = new node;
- //temp = (struct node *)malloc(sizeof(struct node));
- cout << "\nEnter a node data: ";
- cin >> data;
- temp->data = data;
- temp->link = top;
- top = temp;
- break;
- case 2: // pop - print an item from the stack ad delete it
- if(top != NULL) {
- cout << "\nThe poped element is: " << top->data;
- top = top->link;
- } else {
- cout << "\nStack Underflow";
- }
- break;
- case 3: // print all elements of the stack (without deletion)
- temp = top;
- if(temp == NULL) {
- cout << "\nStack is empty\n";
- }
- while(temp != NULL) {
- cout << " -> " << temp->data;
- temp = temp->link;
- }
- break;
- case 4: // goes out from infinite loop and terminate the execution
- return 0;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment