我正在学习如何制作链接列表,但它根本无法打印任何内容,我不明白为什么???请帮忙。我相信这与我的指针有关,但我不知道它是什么。
#include <stdio.h>
#include <stdlib.h>
// typedef is used to give a data type a new name
typedef struct node * link ;// link is now type struct node pointer
/*
typedef allows us to say "link ptr"
instead of "struct node * ptr"
*/
struct node{
int item ;// this is the data
link next ;//same as struct node * next, next is a pointer
};
void printAll(link head); // print a linked list , starting at link head
void addFirst(link ptr, int val ); // add a node with given value to a list
link removeLast(link ptr); // removes and returns the last element in the link
//prints the link
void printAll(link head){
link ptr = head;
printf("\nPrinting Linked List:\n");
while(ptr != NULL){
printf(" %d ", (*ptr).item);
ptr = (*ptr).next;// same as ptr->next
}
printf("\n");
}
//adds to the head of the link
void addFirst(link ptr, int val ){
link tmp = malloc(sizeof(struct node));// allocates memory for the node
tmp->item = val;
tmp->next = ptr;
ptr = tmp;
}
// testing
int main(void) {
link head = NULL;// same as struct node * head, head is a pointer type
//populating list
for(int i = 0; i<3; i++){
addFirst(head, i);
}
printAll(head);
return 0;
}
输出:
打印链接列表:
进程返回 0 (0x0) 执行时间:0.059 s
按任意键继续
最佳答案
这是因为您向函数传递了一个空指针,而退出循环的条件是该指针为空,所以什么也没有发生。
您的 addFirst
函数采用指针的值,但它无法修改您在 main() 内声明的 head
。
要修改 head
,您需要传递一个指向链接的指针,然后您可以取消引用该指针以访问您的 head
,然后您可以更改它。
void addFirst(link *ptr, int val ){
link tmp = malloc(sizeof(struct node));// allocates memory for the node
tmp->item = val;
tmp->next = *ptr;
*ptr = tmp;
}
现在您可以更改头指针。只需记住在调用函数时将地址传递给它即可。 addFirst(&head,i)
关于c - 简单链表无法打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50591229/