Last active
March 2, 2022 23:50
-
-
Save kuntalchandra/ef728a9b9877ec0c72f1774ce9215d33 to your computer and use it in GitHub Desktop.
Stack implementation using Linked List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Implementation of stack using Linked list | |
| * Average Time Complexity | |
| * Insert/delete Θ(1) | |
| * Search Θ(n) | |
| * Space complexity: O(n) | |
| */ | |
| #include <cstdlib> | |
| #include <stdio.h> | |
| #include <malloc.h> | |
| struct node { | |
| int data; | |
| struct node* next; | |
| }*top=NULL; | |
| void push(int value); | |
| int pop(); | |
| void display(); | |
| int main() { | |
| int choice, value; | |
| printf("\nStack implementation using Linked list"); | |
| while(1) { | |
| printf("\n1. Push\n2. Pop\n3. Display\n4. Exit"); | |
| printf("\nEnter your choice:"); | |
| scanf("%d", &choice); | |
| switch(choice) { | |
| case 1: printf("\nEnter the value to push: "); | |
| scanf("%d", &value); | |
| push(value); | |
| break; | |
| case 2: pop(); | |
| break; | |
| case 3: display(); | |
| break; | |
| case 4: exit(0); | |
| default: printf("\nWrong choice!"); | |
| } | |
| } | |
| } | |
| void push(int value) { | |
| struct node *temp_node; | |
| temp_node = (struct node*)malloc(sizeof(struct node)); | |
| temp_node->data = value; | |
| if (top == NULL) { | |
| temp_node->next = NULL; | |
| } else { | |
| temp_node->next = top; | |
| } | |
| top = temp_node; | |
| } | |
| int pop() { | |
| if (top == NULL) { | |
| printf("\nEmpty stack!"); | |
| } else { | |
| struct node *temp_node = top; | |
| printf("\nPopped up: %d", top->data); | |
| top = temp_node->next; | |
| free(temp_node); | |
| } | |
| } | |
| void display() { | |
| struct node *temp_node = top; | |
| if (top == NULL) { | |
| printf("\nStack is empty."); | |
| } else { | |
| while(temp_node->next != NULL) { | |
| printf("\ndata: %d", temp_node->data); | |
| temp_node = temp_node->next; | |
| } | |
| printf("\nLast data: %d", temp_node->data); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment