Implement a stack using linked list

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct stack
{
	int data;
	struct stack *link;
};/*End of struct stack*/
struct stack *top=NULL;
void push();
void pop();
void display();
void main()
{
	int ch;
	while(1)
	{
		clrscr();
		printf("\nPress 1 For Push.");
		printf("\nPress 2 For Pop");
		printf("\nPress 3 For Display");
		printf("\nPress 4 For Exit");
		printf("\nEnter Your Choice: ");
		scanf("%d",&ch);
		switch(ch)
		{
			case 1:
				push();
				break;
			case 2:
				pop();
				break;
			case 3:
				display();
				break;
			case 4:
				exit(0);
			default:
				printf("\nInvalid Choice.. Try Again");
				getch();
		}/*End of switch*/
	}/*End of while*/
}/*End of void main()*/
void push()
{
	struct stack *p;
	p=(struct stack *)malloc(sizeof(struct stack));
	printf("\nEnter Data: ");
	scanf("%d",&p->data);
	if(top==NULL)
	{
		top=p;
		top->link=NULL;
	}/*End of if*/
	else
	{
		p->link=top;
		top=p;
	}/*End of else*/
	printf("\nElement Pushed");
	getch();
}/*End of void push()*/
void pop()
{
	struct stack *node;
	if(top==NULL)
	{
		printf("\nStack Underflow");
		getch();
		return;
	}/*End of if*/
	printf("\n%d Popped.",top->data);
	node=top;
	top=top->link;
	free(node);
	getch();
}/*End of void pop()*/
void display()
{
	struct stack *node;
	if(top==NULL)
	{
		printf("\nStack Is Empty..");
		getch();
		return;
	}/*End of if*/
	node=top;
	printf("\nTop -> ");
	while(node!=NULL)
	{
		printf("%d -> ",node->data);
		node=node->link;
	}/*End of while loop*/
	printf("NULL");
	getch();
}/*End of void display()*/

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *