Created
October 19, 2018 17:02
-
-
Save jamesgeorge007/ff2be135d6bb792fb20d165e0e3a48bb to your computer and use it in GitHub Desktop.
Stack implementation using linked list in C.
This file contains 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
#include<stdio.h> | |
#include<stdlib.h> | |
struct Node | |
{ | |
int data; | |
struct Node* next; | |
}; | |
struct Node* top = NULL; | |
struct Node* temp; | |
int count = 0; | |
void display() | |
{ | |
temp = top; | |
if(count == 0) | |
{ | |
printf("\nStack is Empty!\n"); | |
return; | |
} | |
else | |
{ | |
printf("\nThere are currently %d items:-\n", count); | |
while(temp != NULL) | |
{ | |
printf("%d ", temp->data); | |
temp = temp->next; | |
} | |
printf("\n"); | |
} | |
} | |
void push(int el) | |
{ | |
if(top == NULL) | |
{ | |
top = (struct Node*) malloc(sizeof(struct Node*)); | |
top->data = el; | |
top->next = NULL; | |
} | |
else | |
{ | |
temp = (struct Node*) malloc(sizeof(struct Node*)); | |
temp->next = top; | |
temp->data = el; | |
top = temp; | |
} | |
count++; | |
display(); | |
} | |
void pop() | |
{ | |
temp = top; | |
if(top == NULL) | |
{ | |
printf("\nStack is empty!\n"); | |
exit(1); | |
} | |
else | |
temp = temp->next; | |
printf("\nItem to be removed is %d.", top->data); | |
free(top); | |
top = temp; | |
count--; | |
display(); | |
} | |
int main() | |
{ | |
int choice; | |
int el; | |
while(1) | |
{ | |
printf("\n1.Push\n2.Pop\n3.Display\nChoice: "); | |
scanf("%d", &choice); | |
switch(choice) | |
{ | |
case 1: | |
printf("\nElement to be inserted: "); | |
scanf("%d", &el); | |
push(el); | |
break; | |
case 2: | |
pop(); | |
break; | |
case 3: | |
display(); | |
break; | |
default: | |
printf("\nInvalid Input!\n"); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment