c - 我在 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
。我的推送功能有什么问题吗?
解决方案
之后:
push(5);
push(7);
push(8);
您有以下链表:
5 <- 7 <- 8 <- 缓冲区
弹出后你有: 5 <- 7 <- 缓冲区
这就是为什么buffer->data
是 7 和buffer->next->data
5。
为了以正确的顺序打印列表,您需要一个指向第一个节点的指针。在您的情况下 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;
}
推荐阅读
- apache - 重定向除 htaccess 中的少数路径之外的所有路径
- azure-devops - 重新检查 VSTS (Azure DevOps) 中的合并冲突
- apache-spark - 解决 Spark SQL 中的 Skew 的 Salting 技术
- matlab - 在 MATLAB 中通过回归计算趋势值
- java - 如何以编程方式获取 AppBar 高度?
- c++ - 如何检测类中是否存在特定的 PRIVATE 成员变量?
- c# - 使用按钮在文本框区域中生成一个新的 Guid。(C#)
- javascript - 如何禁用 iOS HTML5 视频控件?
- javascript - 使用 vuejs 框架的单元格中带有路由器链接的 Ag-Grid 链接
- r - 使用 dplyr group_by() 和 distinct() 而不丢失我的变量之一