我是弱链表,所以请帮助我:
我的LinkedList没有在屏幕上显示(显示功能不正常),即使链表正在成功创建,如果我使用node *head
作为指向结构的全局指针,并且如果我用head
(这是node *head
的地址)和LinkedList *list
(在函数参数中)与node *head
替换list->head
,然后它打印整个列表,但如果我使用list->head
或list
代替head
(这是node *head
的地址),并根据node *head
声明LinkedList *list
,那么它将在链表中输入值,但不显示链表。
导致问题的代码如下:
#include<stdio.h>
#include<malloc.h>
typedef struct node{
int data;
struct node *next;
}node;
typedef struct LinkedList_
{
node *head;
} LinkedList;
void create( LinkedList *list ){
char choice='y';
do{
node *newnode,*temp;
newnode=(node*)malloc(sizeof(node*));
printf("nenter the data: ");
scanf("%d",&newnode->data);
newnode->next=NULL;
if(list==NULL){
list->head=newnode;
temp=newnode;
}
else{
temp=list->head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=newnode;
}
printf("ndo you want to continue(y or no)? ");
choice=getche();
}while(choice=='y');
}
void display( LinkedList *list ){
printf("n[");
while(list->head!=NULL){
printf("%d,",list->head->data);
list->head=list->head->next;
}
printf("]");
}
void main(){
LinkedList *head=NULL;
create(head);
display(head);
}
修复如下
#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);
}