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--];
}
我对其进行了更改,以便它存储 int* 而不是 int。
#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;
}
但很明显,因为线路的原因,它不起作用
return INT_MIN;
如何更改此行以使其正常工作?
在第一个变体中,整数存储在堆栈中。如果堆栈中没有可弹出的内容,则返回一些整数(
INT_MIN)。在您的版本中,指向整数的指针存储在堆栈中。在这种情况下,如果无法从堆栈中弹出任何内容,则必须返回一些指针。最简单的 -
NULL。