c - 链表打印功能不起作用

标签 c data-structures linked-list singly-linked-list

这个程序运行没有错误,但它不打印任何东西。我无法找出错误。

我正在学习 C 语言的数据结构,这是学习数据结构的好习惯吗?

提前致谢!!!!!!

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


typedef struct Node
 {
   int data;
   struct Node *next;
 }list_node;


 list_node* push(list_node* head_r, int new_data)
 {
    list_node* new_Node = (list_node*)malloc(sizeof(list_node));

    new_Node->data  = new_data;
    new_Node->next = head_r;
    head_r = new_Node;
    return head_r;
  }

void Print(list_node* head_r)  
 {
   while(head_r)
    {
      printf("%d\n", head_r->data);
      head_r = head_r->next;
    }

  }


int main()
 {

    list_node* l_list = NULL;
  push(l_list, 1);
  push(l_list, 2);
  push(l_list, 6);
  push(l_list, 8);
  push(l_list, 7);
  push(l_list, 3);
  push(l_list, 4);

  printf("Given linked list \n");
  Print(l_list);

  return 0; 
}

最佳答案

您的列表为空,因为未使用推送返回值

你的主应该是这样的:

int main()
 {

    list_node* l_list = NULL;
  l_list = push(l_list, 1);
  l_list = push(l_list, 2);
  l_list = push(l_list, 6);
  l_list = push(l_list, 8);
  l_list = push(l_list, 7);
  l_list = push(l_list, 3);
  l_list = push(l_list, 4);

  printf("Given linked list \n");
  Print(l_list);

  return 0; 
}

或者您可以通过引用传递列表,此时您的代码如下所示:

void push(list_node** head_r, int new_data)
 {
    list_node* new_Node = (list_node*)malloc(sizeof(list_node));

    new_Node->data  = new_data;
    new_Node->next = *head_r;
    *head_r = new_Node;
  }

int main()
 {

    list_node* l_list = NULL;
  push(&l_list, 1);
  push(&l_list, 2);
  push(&l_list, 6);
  push(&l_list, 8);
  push(&l_list, 7);
  push(&l_list, 3);
  push(&l_list, 4);

  printf("Given linked list \n");
  Print(l_list);

  return 0; 
}

关于c - 链表打印功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36712835/

相关文章:

c - 尝试使用 gcc 编译时出错

c - 在C语言实现的Shell中改变颜色

php - 一家送货公司的 Stripe Payments

c - C 错误中的 Printf 链表

链表归并排序的复杂性

C - 需要帮助实现 ADT

c - 宏空白

c - 一行中用空格分隔的 2 个 float 的错误句柄

data-structures - 为什么这个二叉树不是堆?

python - 对象之间无缘无故共享字典?