首页 > 解决方案 > c中的链表问题我不知道为什么它不起作用

问题描述

正如您在我的代码中看到的那样,我要求用户输入一些值(使用防御性编程),然后我想以正确的顺序将这些值放入列表中。如果用户的值是5,4,3列表应该是[5, 4, 3]. 然而这不起作用......也许有一些帮助?

我使用双指针(通过 ref 调用)作为列表头和指向最后一个元素的指针last。这是对的吗?

我的编译器说这是insert函数 ( *last->next = temp;) 中的错误。它具体说request from member 'next' in something not a structure or union

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

struct node {
    int data;
    struct node *next;
};

typedef struct node *Nodeptr;
typedef struct node Node;

void insert(Nodeptr *list, Nodeptr *last, int info) {
    Nodeptr temp;
    temp = (Nodeptr)malloc(sizeof(Node));
    temp->data = info;

    if (!(*list)) {
        temp->next = NULL;
        *list = temp;
        *last = temp; // points to last node
    } else {
        *last->next = temp; //points to last node
        *last = temp;
        *last->next = NULL;
    }
}

void print(Nodeptr list) {
    Nodeptr aux;
    aux = list;

    if (!list) {
        puts("Empty!\n");
    } else {
        while (aux != NULL) {
            printf("%d ", aux->data);
            aux = aux->next;
        }
    }
}

main() {
    Nodeptr head = NULL;
    Nodeptr last;
    int i, num;

    for (i = 0; i < 3; i++) {
        do {
            printf("Give number: ");
            scanf("%d", &num);

            if (num < 10 || num > 99) {
                printf("\nWrong!.");
            }
        } while (!(num >= 10 && num <= 99)); 

        insert(&head, &last, num);
    }

    print(head);

    getch();
}

标签: clinked-list

解决方案


是的,在这种情况下使用双指针是有意义的。

但是,根据运算符优先级的规则,运算符的优先->级高于*运算符。因此,您必须像这样添加括号:

(*last)->next=temp;


推荐阅读