Dynamic Stack Program using Pointers

Previous
Next
#include<stdio.h>
int min, curr;
int *stack, *top;
void createStack();
void push();
void pop();
void traverse();

int main()
{
	int ch;
	createStack();
	
	printf("Stack operations :\n");
	while(1)
	{
		printf("1.Push \n");
		printf("2.Pop \n");
		printf("3.Display \n");
		printf("4.Quit \n");
		
		printf("Enter choice : ");
		scanf("%d", &ch);
		
		switch(ch)
		{
			case 1 : 	push();
				  	break;
			
			case 2	: 	pop();
				  	break;
		
			case 3	: 	traverse();
				  	break;
			
			case 4	: 	exit(1);
			default : 	printf("Invalid choice\n\n");
		}
	}
	return 0;
}

void createStack()
{
	printf("Enter initial size : ");
	scanf("%d", &min);
	curr = min;
	
	stack = (int*)calloc(min, sizeof(int));
	if(stack==NULL)
	{
		printf("Stack creation failed\n");
		exit(0);
	}
	else
	{
		top = stack;	
	}
}
void push()
{
	int ele;
	printf("Enter element to be pushed : ");
	scanf("%d" , &ele);
	if(top==stack+curr)
	{
		++curr;
		stack=(int*)realloc(stack, curr*sizeof(int));
		if(stack==NULL)
		{
			printf("Unable to increase the size \n");
		}
		else
		{
			*top = ele;	
			++top;
			printf("Element pushed...\n");	
		}
	}
	else
	{
		*top = ele;	
		++top;
		printf("Element pushed...\n");
	}
}
void pop()
{
	if(stack==top)
	{
		printf("Stack is Empty\n");
	}
	else
	{
		--top;
		printf("Popped : %d \n", *top);	
		if(curr>min)
		{
			--curr;
			stack = (int*)realloc(stack , curr*sizeof(int));	
		}
	}
}
void traverse()
{
	if(stack==top)
	{
		printf("Stack is Empty\n");
	}
	else
	{
		int* i;
		printf("Stack elements are : \n");	
		for(i=top-1 ; i>=stack ; i--)
		{
			printf("%d \n", *i);
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form