There is an implemented Stack data structure in C.

// C program for array implementation of stack #include <stdio.h> #include <stdlib.h> #include <limits.h> // A structure to represent a stack struct Stack { int top; unsigned capacity; int* array; }; // function to create a stack of given capacity. It initializes size of // stack as 0 struct Stack* createStack(unsigned capacity) { struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack)); stack->capacity = capacity; stack->top = -1; stack->array = (int*) malloc(stack->capacity * sizeof(int)); return stack; } // Stack is full when top is equal to the last index int isFull(struct Stack* stack) { return stack->top == stack->capacity - 1; } // Stack is empty when top is equal to -1 int isEmpty(struct Stack* stack) { return stack->top == -1; } // Function to add an item to stack. It increases top by 1 void push(struct Stack* stack, int item) { if (isFull(stack)) return; stack->array[++stack->top] = item; printf("%d pushed to stack\n", item); } // Function to remove an item from stack. It decreases top by 1 int pop(struct Stack* stack) { if (isEmpty(stack)) return INT_MIN; return stack->array[stack->top--]; } 

I changed it so that it stores int int * instead.

 #include <stdio.h> #include <stdlib.h> #include <limits.h> struct StackNode { int* data; struct StackNode* next; }; struct StackNode* newNode(int* data) { struct StackNode* stackNode = (struct StackNode*) malloc(sizeof(struct StackNode)); stackNode->data = data; stackNode->next = NULL; return stackNode; } int isEmpty(struct StackNode *root) { return !root; } void push(struct StackNode** root, int* data) { struct StackNode* stackNode = newNode(data); stackNode->next = *root; *root = stackNode; printf("%d pushed to stack\n", data); } int* pop(struct StackNode** root) { if (isEmpty(*root)) return INT_MIN; struct StackNode* temp = *root; *root = (*root)->next; int* popped = temp->data; free(temp); return popped; } 

But it is clear that it does not work because of the return INT_MIN;

How to change this line so that it works?

  • 2
    Return NULL if you do not want to react in any other way to an emergency ... - Harry

1 answer 1

In the first variant, integers were stored in the stack. In case there was nothing to extract from the stack, you returned an integer ( INT_MIN ).

In your case, pointers to integers are stored in the stack. In this case, if nothing can be retrieved from the stack, you need to return some pointer . The easiest is NULL .