c - 简单链表无法打印

标签 c linked-list singly-linked-list

我正在学习如何制作链接列表,但它根本无法打印任何内容,我不明白为什么???请帮忙。我相信这与我的指针有关,但我不知道它是什么。

#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/

相关文章:

c - C语言中如何获取指向指针的指针?

C - 代码表示头未声明 - 尝试将节点插入链表

c - 双指针将 char 数组值分配给使用 char 指针的结构的 char 数组

在 C 中创建固定大小的链表

c - BST 第 n 个最小 (C)

c - 赋值中的类型不兼容。 C

c - 打印链表中的节点时无限循环

algorithm - 您将如何从单向链表(一次遍历)中的尾部获取第 n 个节点?

无法在 gcc ubuntu linux 中正确输入字符串

c - 使用 ReadFile 读取整个 PhysicalDrive 内容