我在链表中很弱,所以请帮帮我:
我的LinkedList没有显示在屏幕上(显示功能无法正常工作),即使链接列表正在成功创建,如果我使用node *head
作为结构的全局指针,如果我替换了list->head
使用head
(node *head
的地址)和LinkedList *list
(在函数的参数中)与node *head
,然后它打印整个列表但是如果我使用{{ 1}}或list->head
代替list
(这是head
的地址)并在node *head
中声明LinkedList *list
然后输入值链表但不显示链表。
导致问题的代码如下:
node *head
答案 0 :(得分:2)
像这样修复
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct node{
int data;
struct node *next;
}node;
typedef struct LinkedList_ {
node *head;
} LinkedList;
void create( LinkedList *list ){
char choice='y';
if(!list || list->head){//guard
fprintf(stderr, "Invalid call %s.\n", __func__);
return;
}
node *temp;
do{
node *newnode;
newnode = malloc(sizeof(*newnode));//or malloc(sizeof(node));
printf("\nenter the data: ");
scanf("%d", &newnode->data);
newnode->next = NULL;
if(list->head == NULL){
list->head = newnode;
temp = newnode;
} else {
temp = temp->next = newnode;//There is no need to follow the link
}
printf("\ndo you want to continue(y or no)? ");
choice=getche();
}while(choice=='y');
}
void display( LinkedList *list ){
node *curr = list->head;//head should not be changed
printf("\n[");
while(curr != NULL){
printf("%d,", curr->data);
curr = curr->next;
}
printf("]\n");
}
int main(void){
LinkedList head = { NULL };//requires entity
create(&head);
display(&head);
}