Stack implementation without pointer

Posted

in

by

Stack is a type of data structure, where data is stored in Last In First Out fashion. In embedded system there are different kind of stacks available.
They are implemented in hardware and software.
The hardware implementation of stack is faster than software stack; but the size of stack in hardware is limited.

There are two types of stack available in hardware implementation:
1. Up-counting
2. Down-counting
Up-counting stack: where the memory location of the top element of stack is incremented from the low memory address;
Down-counting stack where the memory location is decremented from the highest memory address.

The following is a general stack implementation program which is written on x86 machine.


#include <stdio.h>

#define MAX 7

int arr[MAX]; // array of size MAX

int top = -1; //top is the index which stores the location
              // of the last inserted element in stack
/*
isFull Function checks that the top == MAX
isEmpty Function checks that the top == -1
*/
int isFull();
int isEmpty();

/*
push(int num)     To insert a element in stack
pop()             To remove the last inserted element in stack
display()         To display all the element in stack
*/

void pop();
void push(int num);

void display();

int main() {

display();	//display the elements of the stack

    push(32);
    push (1);
    push (26);
    push (64);
    push (127);
    push (-98);
    push (43);
    push (5);
    push (255);
    push (5);
    display();
    pop();

return 0;
}

int isEmpty(){
	if(top == -1){
		return 1;
	}
	else
		return 0;
}

int isFull(){
	if(top == MAX){
		return 1;
	}
	else
		return 0;
}

/*check if the stack is full or not.
If stack full 
write overflow
else 
increment the TOP and write the value.
*/
void push(int num){
	if(isFull()){
	printf("Stack Full OverFlow\n");
	}
	else {
		top++;
		arr[top] = num;
	}
	display();
}
/*check if the stack is empty or not.
If stack empty 
write underflow
else 
decrement the TOP.
*/
void pop(){
	if( isEmpty() ) {
	printf("Stack Full OverFlow\n");
	}
	else {
		top--;
	}
	display();
}

void display(){
	if( isEmpty() ){
		printf("Stack Empty UNDERFLOW\n");
		
	}
	else{
		int temp;
		for(temp = top; temp >= 0 ; temp--){
			printf("%d ",arr[temp]);
		}
		printf("\n");
		/*int *ptr = arr;
		while(ptr <= ((&arr)+MAX) ){
			printf("%d ",*ptr);
			ptr = ptr + 1;
			printf("\n");
		}
		*/
		
	}
}

Output Of the above program


Stack Empty UNDERFLOW

32 

1 32 

26 1 32 

64 26 1 32 

127 64 26 1 32 

-98 127 64 26 1 32 

43 -98 127 64 26 1 32 

5 43 -98 127 64 26 1 32 
Stack Full OverFlow

5 43 -98 127 64 26 1 32 
Stack Full OverFlow

5 43 -98 127 64 26 1 32 

5 43 -98 127 64 26 1 32 

43 -98 127 64 26 1 32 

Comments

Leave a Reply

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