打印链接列表

时间:2019-09-28 15:26:36

标签: 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这样的变量,这是我分配给的变量。

1 个答案:

答案 0 :(得分:1)

您正在打印指针,即那些结构的地址。 如果要打印数据,则应打印数据字段:

printf("%d", head->data);

此外,如果您要打印出单链列表的所有元素,则可以执行以下操作:

struct Node* p = head;
while (p != NULL)
{
  printf("%d\n", p->data);
  p = p->next;
}