Wednesday, 7 December 2016

Stack using Linked Lists in C

This is a simple Linked Representation of Stacks in C.
I didn't like the one given in Reema Thareja's book so I made a simpler one.

#include <stdio.h>
#include <stdlib.h>
struct stack {
int data;
struct stack *next;
};
struct stack *top = NULL;
void push(int num) {
struct stack *nn;
nn = (struct stack *)malloc(sizeof(struct stack));
nn -> data = num;
if(top == NULL) {
nn -> next = NULL;
top = nn;
} else {
// Insert at beginning
nn -> next = top;
top = nn;
}
}
int pop() {
int num;
struct stack *temp;
if(top == NULL) {
return -1;
} else {
num = top -> data;
temp = top;
top = top -> next;
free(temp);
return num;
}
}
int peek(){
if(top == NULL) {
return -1;
} else {
return top -> data;
}
}
void display(){
struct stack *p;
if(top == NULL) {
printf("Stack is Empty\n");
} else {
p = top;
printf("The elements in the stack are: \n");
while(p != NULL) {
printf("%d\n", p -> data);
p = p -> next;
}
}
}
int main()
{
int rpt = 1, num, choice;
while(rpt != 0) {
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("--------------\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Enter number: ");
scanf("%d", &num);
push(num);
break;
case 2:
num = pop();
if(num != -1) {
printf("%d deleted from stack\n", num);
} else {
printf("Stack Underflow\n");
}
break;
case 3:
num = peek();
if(num != -1) {
printf("Element on top of the stack = %d\n", num);
} else {
printf("Stack Underflow\n");
}
break;
case 4:
display();
break;
case 5:
exit(0);
}
printf("Do you want to continue? (1/0): ");
scanf("%d", &rpt);
system("cls");
}
return 0;
}

No comments:

Post a Comment