stack Algorithm

The stack using a doubly linked list (DLL) algorithm is a dynamic data structure that stores a collection of elements in a linear fashion, where each element has a reference to the element before and after it. This stack allows for the efficient management of elements by performing insertions and deletions at the beginning or end of the list without affecting the rest of the elements. A commonly used analogy to describe a stack is a stack of plates, where you can only add or remove a plate from the top of the stack. This behavior is known as Last-In, First-Out (LIFO), which means that the most recently added element is always the first one to be removed. Implementing a stack using a doubly linked list offers several advantages over other data structures like arrays. First, it allows for dynamic resizing, which means that the stack can grow or shrink in size as elements are added or removed. This makes it more memory-efficient, as the stack only uses the exact amount of memory needed to store its elements. Second, the time complexity for inserting and deleting elements in a DLL-based stack is O(1), which makes these operations quite fast. However, this comes at the cost of increased complexity in managing the pointers for the previous and next elements in the list, which can make the implementation more challenging than using an array-based stack.
//
//  A Stack is an abstract data type that serves as a collection
// of elements, with two principal operations are push & pop
//
// The All ▲lgorithms Project
//
// https://allalgorithms.com/data-scructures/
// https://github.com/allalgorithms/cpp
//
// Contributed by: ANUJ MODI
// Github: @descifrado
//
#include<stdio.h>
#define max 50
struct stack
{
	int ch[max];
	int top;
};
typedef struct stack Stack;
void push(Stack *s, int x)
{
	if(s->top==max-1)
		printf("ERROR: Stack Overflow\n");
	else
		s->ch[++s->top]=x;
}
int pop(Stack *s)
{
	if(s->top==-1)
	{
		printf("ERROR: Stack Underflow\n");
	}
	else
		return (s->ch[s->top--]);
}
int main()
{
	printf("Stack Has Been Initiated...\n");
	Stack s;
	s.top=-1;
	int c;
	while(1)
	{
		printf("\nEnter 1 to push an element\nEnter 2 to pop an element\nEnter 3 to display all the content of stack\nEnter 0 to exit\n");
		scanf("%d",&c);
		switch(c)
		{
			case 0: return 0;
			case 1:
			{
				printf("Enter element to be pushed\n");
				int x;
				scanf("%d",&x);
				push(&s,x);
				printf("Element successfully pushed\n");
				break;
			}
			case 2:
			{
				printf("Poped Element Is %d\n",pop(&s));
				break;
			}
			case 3:
			{
				printf("Stack has the following content in order LIFO\n");
				int i;
				for(i=s.top;i>=0;i--)
				{
					printf("%d ",s.ch[i]);
				}
				break;
			}
			default:
			{
				printf("Wrong Choice\n");
			}
		}
	}
}

LANGUAGE:

DARK MODE: