gpt4 book ai didi

c - c中栈数据结构解释

转载 作者:行者123 更新时间:2023-11-30 21:47:57 25 4
gpt4 key购买 nike

我在网上看到了这段代码,但并没有完全理解它。有人可以详细解释一下推送、弹出和查看部分吗?这些是我最疑惑的部分。或者,更好的是,如果您能为我提供一些详细教授数据结构和指针的链接,那就太好了。

// 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--];
}

// Function to get top item from stack
int peek(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top];
}

// Driver program to test above functions
int main()
{
struct Stack* stack = createStack(100);

push(stack, 10);
push(stack, 20);
push(stack, 30);

printf("%d popped from stack\n", pop(stack));

printf("Top item is %d\n", peek(stack));

return 0;
}

谢谢!!

最佳答案

这是一个值得阅读的精彩页面...

http://www.c4learn.com/data-structure/basic-stack-concept/

我无法从中获取片段 - 因为它充满了图像,并且以一种很好的方式完成,可以充分理解堆栈及其工作原理。

这将使您能够掌握您在问题中发布的代码。

关于c - c中栈数据结构解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31723203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com