Operations on Stack

Here are the common operations that can be performed on a stack in C language:

Push

The push operation adds a new element to the top of the stack. The prototype of the push function is as follows

void push(int item);

Where item is the data item to be added to the stack.

Pop

The pop operation removes the top element from the stack. The prototype of the pop function is as follows

int pop();

The pop function returns the data item that was removed from the stack.

Peek

The peek operation returns the top element of the stack without removing it. The prototype of the peek function is as follows

int peek();

The peek function returns the data item at the top of the stack.

isEmpty

The isEmpty operation checks if the stack is empty. The prototype of the isEmpty function is as follows

int isEmpty();

The isEmpty function returns 1 if the stack is empty and 0 otherwise.

isFull

The isFull operation checks if the stack is full. This operation is only applicable when the stack is implemented using an array. The prototype of the isFull function is as follows

int isFull();

The isFull function returns 1 if the stack is full and 0 otherwise.

Here is an example implementation of these operations

#define MAX_SIZE 100

int stack[MAX_SIZE];
int top = -1;

void push(int item) {
    if (top >= MAX_SIZE - 1) {
        printf("Stack Overflow\n");
    } else {
        top++;
        stack[top] = item;
    }
}

int pop() {
    int item;
    if (top < 0) {
        printf("Stack Underflow\n");
        return -1;
    } else {
        item = stack[top];
        top--;
        return item;
    }
}

int peek() {
    if (top < 0) {
        printf("Stack is Empty\n");
        return -1;
    } else {
        return stack[top];
    }
}

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

int isFull() {
    if (top >= MAX_SIZE - 1) {
        return 1;
    } else {
        return 0;
    }
}

Add a Comment

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