首页 > 解决方案 > 为什么此 printList 函数不适用于 C 中的链接列表

问题描述

嗨,这是我关于堆栈溢出的第一个问题。我是一名软件工程专业的学生,​​我刚刚开始了解链表。我目前只是为了更好地理解链表,所以请放轻松。这应该是一个基本概念,但对我来说理解起来有些困难。有没有人可以向我解释为什么 printList 函数不为我遍历列表。我已经看到了可行的示例,但我真的很想了解为什么我的逻辑不适用于此功能。

我的代码在下面,我正在使用 gcc 编译我的代码,不太确定这会有所作为

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


struct node{
    int data;
    struct node* next;

}node;


void printList(struct node *head){
    struct node *temp = head;
    while(temp->next != NULL){
        printf("Here\n");
        printf("%d - ",temp->data);
        temp = temp->next;
    }

    printf("\n");
}

//this will create a new node and return a new created node
//data will be set to zero
//next pointer is set to null
struct node createNode(){
    struct node temp;
    temp.data = 0;
    temp.next = NULL;
    return temp;
}

//this will add a node to the beginning of the list
//you will need to pass a new head and pass the data you want stored of type int
//this will return a type node
struct node addNode(struct node head,int data){
    struct node temp;
    struct node ptr;

    temp = createNode();
    temp.data = data;

    if(head.next == NULL){//whent the list is empty
        head = temp;
    }else{
        ptr = head;
        while(ptr.next !=NULL){
            ptr = *ptr.next;//this will traverse the list until it reaches the end
        }
            ptr.next = NULL;
            head.next = ptr.next;
    }
    printf("Added: %d\n",temp.data);
    return head;

}

int main(){

    struct node head = createNode();
    struct node *temp = &head;

    int userNum;

    while(userNum != -1){
        printf("Enter a number to add to the linked list: ");
        scanf("%d",&userNum);

        if(userNum == -1){//this will end the loop
            break;
        }else{
            addNode(*temp,userNum);
        }

    }


    printList(temp);


    return 0;
}

我的 addNode 函数有效,但我不明白为什么 printList() 不会打印任何内容。如果这有什么不同,我将使用 gcc 作为我的编译器。

标签: c

解决方案


我认为您的 addNode 和 createNode 函数存在一些问题。当你想访问指向结构属性的指针时,你必须使用'->'。你必须使用'。当您处理普通结构(不是指针)时。您可以将 malloc 用于 createNode 函数,因为您将处理一个应用了某个指针的链表。而在 addNode 函数中,你可以在参数中使用 *head 而不是 head,因为你正在处理指向结构的指针,你可以将 temp 和 ptr 更改为 *temp 和 *ptr。


推荐阅读