链表打印功能不起作用

时间:2016-04-19 08:31:38

标签: 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; 
}

2 个答案:

答案 0 :(得分:3)

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

你的主人应该这样:

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; 
}

答案 1 :(得分:2)

更改main功能中的行:

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);

您返回的新节点push但未保存在任何位置,因此main中的列表始终为空。

相关问题