Chapter - 11: Structures

A stack is a data structure in which the addition of a new element or deletion of an existing element always takes place at the same end. This end is often known as ‘top’ of the stack. This situation can be compared to a stack of plates in a cafeteria where every new plate taken off the stack is also from the ‘top’ of the stack. There are several application where stack can be put to use. For example, recursion, keeping track of function calls, evaluation of expressions, etc. Write a program to implement a stack using a linked list.


#define GetSize (struct node*)malloc(sizeof(struct node))

void push(struct node**, int);
int pop(struct node**);

struct node
	int data;
	struct node* next;

int main()
	char ans = 'y';
	int num, exit = 1, action;
	struct node *top = NULL;
	printf("\nHello all, this program is of stacks using linked list, so");
	printf("go ahead and make your linked list that will saved in stacks.\n\n");
	while (ans == 'y')
		printf("\nEnter the data : ");
		scanf("%d", &num);
		push(&top, num);
		printf("\nWant to enter another number (y/n) : ");
		while (getchar() != '\n');
		scanf("%c", &ans);
	while (exit != 0)

		printf("\n\n\nYou are in menu section\n\n");
		printf("\n0 : Exit\n1 : Push\n2 : Pop");
		printf("\n\n\nEnter your choice : "); +
			scanf("%d", &action);
		switch (action)
		case 0:
			printf("\nYou are exiting. . . .");
			return 0;
		case 1:
			printf("\nEnter number : ");
			scanf("%f", &num);
			push(&top, num);
		case 2:
			if (num == NULL)
				printf("\nStack is empty");
			num = pop(&top);
			printf("\n\n%d is popped.", num);
			printf("\nYou have entered a wrong option\,Try againA!!\n");
			exit = 1;
	return 0;

/*Push means adding an element in the stack*/
void push(struct node **top, int num)
	struct node *temp = NULL, *help = NULL;
	help = GetSize;

	if (help == NULL)
		printf("\nStack is full!!");

	help->data = num;
	help->next = *top;

	/*Last added element is always the top element.*/
	*top = help;

/*Pop means isolating the top element from the stacks.*/
int pop(struct node **top)
	struct node *temp = GetSize;
	int num;
	if (*top == NULL)
		return NULL;
	num = (*top)->data;
	temp = *top;
	*top = (*top)->next;
	return num;

© 2021 Garbage Valuegarbage value logo