首页 > 解决方案 > 我在 C 中创建了一个推送和弹出函数,但不知道如何按顺序打印它们

问题描述

我最近研究了链表并尝试创建一个推送和弹出功能。

我已经成功地创建了一个看起来像这样的。

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

struct node{
  int data;
  struct node *next;
};

struct node* buffer = NULL;

void push(int elem){
  struct node *new_element = (struct node*)malloc(sizeof(struct node));
  new_element->next = buffer;
  new_element->data = elem;
  buffer = new_element;
}

int pop(void){
  int elem = buffer->data;
  struct node *eliminate = buffer;
  buffer = eliminate->next;
  free(eliminate);
  return elem;
}

之后我尝试以这种方式打印它们:

int main(void) {
  push(5);
  push(7);
  push(8);
  pop();
  printf("%d %d", buffer->data, buffer->next->data);
}

但是,结果7 5不是5 7。我的推送功能有什么问题吗?

标签: clinked-liststack

解决方案


之后:

push(5);
push(7);
push(8);

您有以下链表:

5 <- 7 <- 8 <- 缓冲区

弹出后你有: 5 <- 7 <- 缓冲区

这就是为什么buffer->data是 7 和buffer->next->data5。

为了以正确的顺序打印列表,您需要一个指向第一个节点的指针。在您的情况下 5. 同样使用您的方法,您应该将其设为双链表。

struct node{
  int data;
  struct node *next;
};

struct node* start = NULL;
struct node* buffer = NULL;

void push(int elem){
  struct node *new_element = (struct node*)malloc(sizeof(struct node));
  new_element->next = buffer;
  new_element->data = elem;
  if (buffer == NULL) start = new_element; // this is the magic
  buffer = new_element;
}

推荐阅读