有人可以帮助我了解以下函数中发生了什么吗? 具体使用s1->top?在 push &pop & display 函数中 s1->top 的移动是什么?因为如果在函数 push 中,每当一个数字被压入时 s1->top 都会向右移动?那为什么在display函数中说s1->top在先遍历,而在push中s1->top在n个右边,而在打印值时,我们需要先在左边然后遍历..为什么?
Stack createStack() {
Stack s1;
s1 = (Stack) malloc(sizeof(Stack_Head));
s1 - > count = 0;
s1 - > top = NULL;
return s1;
}
Nodeptr createNode(dataitem item) {
Nodeptr temp;
temp = (Nodeptr) malloc(sizeof(Node));
temp - > data = item;
temp - > next = NULL;
return temp;
}
void push(Stack s1, dataitem item) {
Nodeptr temp = createNode(item);
temp - > next = s1 - > top;
s1 - > top = temp;
s1 - > count++;
}
void display(Stack s1) {
Nodeptr ptr = s1 - > top;
while (ptr1 = NULL) {
printf("%d", ptr - > data);
ptr = ptr - > next;
}
printf("\n");
}
void pop(Stack s1) {
Nodeptr temp;
if (isEmpty(s1))
printf("List is Empty");
else {
temp = s1 - > top;
s1 - > top = temp - > next;
temp - > next = NULL;
free(temp);
s1 - > count;
}
int isEmpty(Stack s1) {
return s1 - > top == NULL;
}
最佳答案
这个栈结构是一个LIFO , s1->top
是栈顶,即最后压入的元素。每个元素都指向堆栈中的下一个元素。
比如这里,push
函数创建了一个指向数据的新元素,让这个新元素指向最后插入的元素(也就是它在栈中的下一个元素),并把栈顶的新元素(s1->top = new_node
,这里的新节点叫做temp
)。
关于有人可以帮助我了解以下功能中发生了什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43206465/