Data Structures & Algorithms(Stack implementation using C)

Sivaganesh Pavithiran
2 min readFeb 26, 2023

--

The data structure is the structural representation of logical relationships between elements of data.

The algorithm is a step–by–step finite sequence of instructions to solve a well-defined computational problem.

Algorithms + Data Structure = Program

Stacks

It is a linear data structure that allows insertion and deletion operations from one end.

LIFO- Last In First Out
So, the last element pushed onto the stack is always the first that will be popped from the stack.

Operations in Stacks:

  1. CreateStack — Initializes the stack to an empty state.
  2. IsStackEmpty — Determines whether the stack is empty. If the stack is empty, it returns the value true; otherwise, it returns the value false.
  3. IsStackFull — Determines whether the stack is full. If the stack is full, it returns the value true; otherwise, it returns the value false.
  4. Push — Adds a new element to the top of the stack. The input to this operation consists of the stack and the new element. Prior to this operation, the stack must exist and must not be full.
  5. Top — Returns the top element of the stack. Prior to this operation, the stack must exist and must not be empty.
  6. Pop — Removes the top element of the stack. Prior to this operation, the stack must exist and must not be empty.

Implementing Stacks using Arrays

First, the array size must be defined based on the number of stack elements required. Then, declare the variables needed.

#define MAXSTACK 50

typedef char stackEntryType;
typedef enum{false,true} boolean;

typedef struct{
int top;
stackEntryType entry[MAXSTACK];
} stack;

Enumeration (or enum) is a user-defined data type in C.

  1. Create Stack Operation
    Initializes the stack to an empty state.
void CreateStack(stack *s){
s->top=-1; }

2. Push Operation
Prior to this operation, the stack must exist and must not be full. If the stack is full, “Stack is Full” will be displayed.

boolean IsStackFull(stack *s){
return (s->top==MAXSTACK-1);
}
void Push(stackEntryType item, stack *s){
if(IsStackFull(s)){
printf("Stack is Full");
exit(1);}
else
s->entry[++s->top]=item;
}

3. Pop Operation
Prior to this operation, the stack must exist and must not be empty. If the stack is empty, “Stack is Empty” will be displayed.

boolean IsStackEmpty(stack *s){
return (s->top==-1);
}
void Pop(stack *s, stackEntryType *item){
if(IsStackEmpty(s)){
printf("stack is Empty");
exit(1);
}
else
*item=s->entry[s->top--];
}

References:

  1. (2023). Javatpoint.com. https://static.javatpoint.com/ds/images/applications-of-stack-in-data-structure.png

--

--