Home > database >  Algorithm to push/insert to stack
Algorithm to push/insert to stack

Time:12-29

Newbie to C here and following online book tutorials. (I have been attempting linked-lists but little complex for now, will return to these later.) I have the following algorithm:

Algorithm: PUSH (STACK, ITEM)
[STACK is an array of MAXSIZE and ITEM is an item to be pushed onto
stack]
1. [Check for stack overflow]
If TOP = MAXSIZE - 1 then
a) Print: Overflow
b) Return
2. [Increase top by 1]
Set TOP = TOP   1
3. [Insert item in new top position]
Set STACK[TOP] = ITEM
4. Return

However, I cannot understand step 1, for Top, how would I go about initialising this, because Top should indicate some pre-existing value? For example:

(My attempt)

#include <stdlib.h>
#include <stdio.h>

int push(int item, int(*stack)[item]){
    int top;
    if(top == sizeof(*stack)/sizeof(*stack[0])-1){
        printf("Overflow");
        return -1;
    }
    top  ;
    *stack[top] = item;
    return **stack;
}

int main(void){
    int arr[4] = {0 , 1, 2, 3};
    int itm = 2;
    int result;
    result = push(itm, &arr);
    printf("\nResult: %i", result);
    return 0;
}

Would always produce an overflow

CodePudding user response:

You will simply need to store the current value of top and send it along with the stack everywhere. You should define a struct, like so:

typedef struct Stack {
    int stack[16]; // Replace 16 with desired capacity.
    int top;
} Stack;

Create a new stack like this:

Stack s = { .top = -1 };

Now all your functions should receive a pointer to this stack, and functions like push should update the value of top.

  • Related