c语言 - s1->top 在以下功能中的移动和起点,推送、显示和弹出



有人可以帮助我了解以下函数中发生了什么吗?具体来说使用s1->top?s1->top 在 push &pop & display 功能中的移动是什么?因为如果在函数推送中,每当按下数字时,s1->top 都会向右移动?那么为什么在显示函数中,它说 S1->top 首先在遍历中,而在推 S1->Top 中是 N 在右边,而在打印值时,我们需要先在左边,然后遍历。.为什么?

typedef struct node* Nodeptr;
typedef char dataitem;
typedef struct node{
dataitem data;
Nodeptr next;
}Node;
typedef struct{
int count;
Nodeptr top;
}Stack_Head;
typedef Stack_Head* Stack;
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 (ptr != 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;
} 

首先,让我们修复一个错误 - 在函数display()中,我假设以下行:

while (ptr1 = NULL) {

真的应该是:

while (ptr != NULL) {

在您的问题中,您提到了"左"和"右",但正如变量"top"所暗示的那样,可视化垂直堆栈更容易。

例如,想象一堆餐盘。 新盘子总是被"推"到顶部,并且根据需要它们也会从顶部"弹出"。

如您所见,这种堆栈称为后进先出(或 LIFO)堆栈,这就是您的代码正在实现的内容。

s1->top变量是指向堆栈顶部的指针 - 即添加的最后一个节点,该节点也将是第一个被删除的节点。 每个节点还有一个指向"在其下方"的next节点的指针。 NULL 用于表示"没有更多的节点",无论是s1->top,还是node->next指针。

所以在push()中,为了保持一致性,必须做两件事:

  1. 新到达的->next指针必须设置为当前 堆栈的"顶部"(因此现有顶部"低于"新到货), 和
  2. 新到货必须设置为新的"顶部"。

请注意,这里的操作顺序很重要 - 如果 (2) 是在 (1) 之前执行的,那么你最终可能会得到新到达的"->next"指针指向自身!

pop()基本上反向执行这些操作,display()简单地运行堆栈中的所有元素(请注意,display()不会更改s1->top的值)。

我不知道你的问题, 在修复代码中的一些错误点击后,例如while(ptr1 = NULL)while(ptr != NULL), 和printf("%f")-"%c"

对于此代码

int main() {    
Stack a = createStack();    
push(a, 'a');
push(a, 'b');
push(a, 'c');
push(a, 'd');
push(a, 'e');    
display(a);
return 0;
}

我得到了正确的输出

//edcba