Get Website Learn Coding Tech Story

C Programming Examples

#include<stdio.h>
#include<stdlib.h>
#define MAX 5

/* Stack structure */
struct stack {
	int data;
	struct stack *link;
} *top = NULL, *node = NULL, *temp = NULL;

/* Function for count length of the Stack */
int stack_count() {
	int count = 0;
	temp = top;
	while(temp != NULL) {
		count++;
		temp = temp->link;
	}
	return count;							
}
										
/* Function for Push data into the Stack */
void push() {

	/* Dynamic memory allocation */
	node = (struct stack*)malloc(sizeof(struct stack));
	if(stack_count() <= MAX - 1) {
		printf("Enter value for stack:\n");
		scanf("%d", &node->data);
		node->link = top;
		top = node;
		printf("Data push into stack successfully!\n");
	}
	else
		printf("Warring: Stack is FULL!\n");					
}

/* Function for Pop data from Stack */
void pop() {
	if(top != NULL) {
		node = top;
		printf("Value %d will popped out of the stack!\n", node->data);
		top = node->link;
		free(node);
	}
	else
		printf("Stack is Empty!\n");
}
										
/* Function for Display data of the Stack */
void display() {
	node = top;
	printf("List of data into the stack:\n");
	while(node != NULL) {
		printf("%d\n", node->data);
		node = node->link;
	}					
}

int main() {
	int op = 0;
	while(op != 4) {
		printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
		printf("Enter your choice:\n");
		scanf("%d", &op);
		switch(op) {
			case 1:
				push();
				break;
			case 2:
				pop();
				break;
			case 3:
				display();
				break;
			case 4:
				printf("Bye Bye!\n");
				exit(0);
				break;
			default:
				printf("Invalid choice!\n");
		}
	}
	return 0;
}


          /****** Output ******/
          

1. Push


2. Pop


3. Display


4. Exit


Enter your choice:


1


Enter value for stack:


5


Data push into stack successfully!


1. Push


2. Pop


3. Display


4. Exit


Enter your choice:


1


Enter value for stack:


6


Data push into stack successfully!


1. Push


2. Pop


3. Display


4. Exit


Enter your choice:


1


Enter value for stack:


7


Data push into stack successfully!


1. Push


2. Pop


3. Display


4. Exit


Enter your choice:


2


Value 7 will popped out of the stack!


1. Push


2. Pop


3. Display


4. Exit


Enter your choice:


3


List of data into the stack:


6


5


1. Push


2. Pop


3. Display


4. Exit


Enter your choice:


4


Bye Bye!

Learn more about Stack Data Structure