gpt4 book ai didi

c - 如何在C编程中使用链表将堆栈链接到其他堆栈?

转载 作者:行者123 更新时间:2023-11-30 14:48:02 25 4
gpt4 key购买 nike

我使用链表创建了自己的堆栈。但我认为这是错误的。我的推送方法是将 Stack1 链接到其他堆栈。所以,我认为这就像......

In my main function,

push(stack1, 10);
push(stack1, 20);

[Stack1] -> [nextStack]
[Stack1] -> [nextStack] (new address from first nextStack)

所以,就像...我一次又一次地重复将 stack1 链接到其他堆栈...

这是我使用下面的链接列表代码的堆栈。

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

typedef struct{
int data;
struct stack *top;
}stack;

void push(stack *currentStack, int data){

if (currentStack->top == NULL)
fprintf(stderr, "Stack is emtpy");

else{
stack *nextStack = (stack*)malloc(sizeof(stack));
currentStack->data = data;
currentStack->top = nextStack;

printf("currentStack is %d\n", currentStack->data);
}
}

int main(){

stack* stack1;
stack1 = (stack*)malloc(sizeof(stack));

push(stack1, 10);
push(stack1, 20);

return 1;
}

这是我的代码的结果。

currentStack is 10
currentStack is 20

最佳答案

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

struct stack
{
int data;
struct stack *top;
} *head = NULL;


void push(int data)
{
if (head == NULL) //that means stack is empty
{
head =(struct node *)malloc(1*sizeof(struct node));
head->top = NULL;
head->data = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->top = head;
temp->data = data;
head = temp;
}

}

您的 push() 函数不完整。它应该考虑两种情况,一种是堆栈为空,另一种是非空。

此外,push() 函数中也不需要传递堆栈指针,因为默认情况下,push() 函数会将新元素推送到最顶层的节点上并且只有一个堆栈。

此外,您还没有使用NULL初始化堆栈指针。这可能会在程序运行期间给您带来未定义的行为。

关于c - 如何在C编程中使用链表将堆栈链接到其他堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50783880/

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