← All resources

Write a program in C to implement a Linked List Based Stack:

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
typedef struct node
{
	int d;
	struct node *link;
}Node;
Node *head=NULL;
void append()
{
	Node *p, *q;
	int x;
	p = (struct node *)malloc(sizeof(struct node));
	p->link = NULL;
	printf("nEnter a value to add at the end:");
	scanf("%d", &p->d);
	if(head==NULL)
	{
		head=p;
		return;
	}
	q = head;
	while(q->link!=NULL)
	{
		q = q->link;
	}
	q->link = p;
}
void del_end()
{
	Node *q, *r;
	if(head==NULL)
	{
		printf("nCannot delete. Linked List is empty.");
		return;
	}
	if(head->link==NULL)
	{
		printf("nDeleted value: %d", head->d);
		q = head;
		head=NULL;
		free(q);
		return;
	}
	r = head;
	q = head->link;
	while(q->link!=NULL)
	{
		r = q;
		q = q->link;
	}
	printf("nDeleted value: %d", q->d);
	r->link=NULL;
	free(q);
}
void display()
{
	Node *q;
	q = head;
	printf("nThe values in the linked list are: n");
	while(q!=NULL)
	{
		printf("%dn", q->d);
		q = q->link;
	}
}
void main()
{
	int ch;
	clrscr();
	do
	{
		printf("nMENU FOR STACK");
		printf("n1. Push");
		printf("n2. Pop.");
		printf("n3. Display");
		printf("n0. Terminate the program.");
		printf("nEnter your choice:");
		ch = getche()-48;
		switch(ch)
		{
			case 1:
			append();
			break;
			case 2:
			del_end();
			break;
			case 3:
			display();
			break;
			case 0:
			printf("nThank you for using the program.");
			break;
			default:
			printf("nInvalid Input Enter Again.");
		}//End of Switch-Case
		getch();
	}while(ch!=0);
	getch();
}