c - 打印链接列表
问题描述
我试图打印在节点中分配的变量,但它打印随机数据。
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node * next;
};
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head -> data = 1;
head -> next = second;
second -> data = 2;
second -> next = third;
third-> data = 3;
third -> next = NULL;
printf("%d",head);
printf("\n%d",second); //problem in this part
printf("\n%d",third);
return 0;
我期待像 1,2,3 这样的输出,它们是我分配给的变量。
解决方案
您正在打印指针,即这些结构的地址。如果要打印数据,则应打印数据字段:
printf("%d", head->data);
另外,如果你想打印出单链表的所有元素,你可以这样做:
struct Node* p = head;
while (p != NULL)
{
printf("%d\n", p->data);
p = p->next;
}
推荐阅读
- python - 使用 python pandas 从 Dataframe 中删除记录
- amazon-web-services - 如何从快照中恢复 ebs
- laravel-5 - 如何解决 Laravel 页面上传到主机后无法正常加载的问题
- javascript - 单击 2 个按钮中的顶部按钮
- javascript - 如何按类名及其所有子标签提取标签
- vb.net - 启动程序时Form1_load代码不起作用
- r - 给定一个包含时间延迟的数据帧:如何判断 90% 的延迟发生在哪一点
- linux - 终端中的脚本输出与 MOTD 输出不同
- ios - 致命错误:init(coder:) 尚未实现。运行时错误在哪里
- python - 我对 Python 中的列表有疑问。列表索引超出范围