c - 以下函数中s1->top的移动和起点,push、display和pop

标签 c stack

有人可以帮助我理解以下函数中发生了什么吗?具体使用s1->top?那么push&pop&display函数中s1->top的 Action 是怎样的呢?因为如果在函数push中,每当有数字被push时,s1->top就会向右移动?那为什么在显示函数中说s1->top先遍历,而在push中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) {

在您的问题中,您引用了“左”和“右”,但正如变量“顶部”所暗示的那样,更容易可视化垂直堆栈。

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

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

s1->top 变量是指向堆栈顶部的指针 - 即。最后添加的节点,也将是第一个被删除的节点。每个节点还有一个指向其“下”下一个节点的指针。 NULL 用于指示“不再有节点”,对于 s1->topnode->next 指针都是如此。

因此,在 push() 中,为了保持一致性,必须发生两件事:

  1. 新到达的->next指针必须设置为当前 堆栈的“顶部”(因此现有顶部位于新到达的“下方”), 和
  2. 新来的必须设置为新的“顶部”。

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

pop() 基本上以相反的方式执行这些操作,而 display() 只是运行堆栈中的所有元素(请注意 display() 不会改变 s1->top 的值。

关于c - 以下函数中s1->top的移动和起点,push、display和pop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43269395/

相关文章:

c++ - 如何拥有按值 vector 并结合使用指针 vector ?

c - 无法在结构中输入值

c - 在 C 套接字中获取客户端的 IP 地址

c - 被覆盖的字符串数组

c - 使用缓冲区溢出覆盖位于缓冲区下方的局部变量

使用列内的固定效果信息 reshape R 中的数据

c++ - 带有 if 语句的嵌套 for 循环的时间复杂度

c - 替换字符串中的单词

java - 将 int 存储到 char 数组中

c - 链接和堆栈的行为