Data Structures Practical 17
Question 1
Write a C program to perform following operations on Stack as Linked List. PUSH (10), PUSH (20), POP, PUSH (10), PUSH (20), POP, PUSH (20), POP.
stack.c
C
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct stack
{
int element;
struct stack *next;
};
struct stack *top = NULL;
void push(int);
int pop();
void display();
void main()
{
int poppedVal;
clrscr();
printf("--- Executing Sequential Linked Stack Operations ---\n\n");
printf("Operation: PUSH(10)\n");
push(10);
display();
printf("Operation: PUSH(20)\n");
push(20);
display();
printf("Operation: POP\n");
poppedVal = pop();
if (poppedVal != -1) printf("Popped: %d\n", poppedVal);
display();
printf("Operation: PUSH(10)\n");
push(10);
display();
printf("Operation: PUSH(20)\n");
push(20);
display();
printf("Operation: POP\n");
poppedVal = pop();
if (poppedVal != -1) printf("Popped: %d\n", poppedVal);
display();
printf("Operation: PUSH(20)\n");
push(20);
display();
printf("Operation: POP\n");
poppedVal = pop();
if (poppedVal != -1) printf("Popped: %d\n", poppedVal);
display();
printf("\nExecution completed. Press any key to exit...");
getch();
}
void push(int value)
{
struct stack *ptr;
ptr = (struct stack *)malloc(sizeof(struct stack));
ptr->element = value;
ptr->next = top;
top = ptr;
return;
}
int pop()
{
int num;
struct stack *temp;
if (top == NULL)
{
printf("\nSTACK is Empty.");
return -1;
}
else
{
num = top->element;
temp = top;
top = top->next;
free(temp);
return (num);
}
}
void display()
{
if (top == NULL)
{
printf("Stack is empty\n");
return;
}
struct stack *ptr1 = NULL;
ptr1 = top;
printf("Current Stack Status: ");
while (ptr1 != NULL)
{
printf("%d\t", ptr1->element);
ptr1 = ptr1->next;
}
printf("\n----------------------------------------\n");
}
Output
