【发布时间】:2018-06-10 12:52:46
【问题描述】:
我使用链表制作了自己的堆栈。但我认为这是错误的。 我的推送方法是将 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
【问题讨论】:
-
至少你永远不会初始化你分配的结构,所以当你使用它时你会得到未定义的行为。使用调试器会立即向您展示这一点,因此请从一开始就学习如何使用它。
-
@Sami 好的。我觉得我没有任何基础。真的感谢。我会调查的!
标签: c data-structures linked-list stack