Menu Close

Stack using Pointers

Stack Implementation using pointers:

  • In this implementation we use dynamic functionality of arrays.
  • Dynamic stack means, the Stack with specified initial capacity and the capacity shrinks and grows depends or insertion and deletion of elements.
  • We use DMA functionality of stdlib.h header file such as calloc(), realloc() and free()
  • Dynamic stack operations can be performed using Pointers.
  • Stack and TOP are pointer type variables in Dynamic Stack implementation.
  • The code program as follows:
#include<stdio.h>
int size;
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", &size);
	
	stack = (int*)calloc(size, 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+size)
	{
		++size;
		stack=(int*)realloc(stack, size*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(size>5)
		{
			--size;
			stack = (int*)realloc(stack , size*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);
		}
	}
}