繁体   English   中英

如何从链接列表中获取数据部分进行比较?

[英]How do you get a data section from a Linked list to compare?

我刚刚开始学习链表,并弄乱了它,但后来遇到了一个问题。 我不确定如何访问数据成员进行实际比较。 在我的代码中,我提示用户输入成绩,当他们输入-1时,它表示已完成成绩。 我的第一个想法是像在scanf中那样获得指向节点的指针以获取数据,但是我无法将指针与整数进行比较。 有没有办法让链表中的数据成员进行比较? 另外,指出其他错误也将不胜感激,因为我不太了解链表。 我有以下代码:

int main() {
    struct Node
    {
        int grade;
        struct Node *next;
    };

    struct Node *head;
    struct Node *first;
    struct Node *temp = 0;
    first = 0;

    while (****** != -1) {       //This is what I need the data from linked list for
        head = (struct Node*)malloc(sizeof(struct Node));
        printf("Enter the grade: \n ");
        scanf("%d", &head -> grade);
        if (first != 0) {
            temp -> next = head;
            temp = head;
        }
        else
        {
            first = temp = head;
        }
    }
}

您的代码有很多问题:

1)不要直接扫描到列表中-使用临时变量

2)始终检查返回值

3)确保初始化变量,即head

尝试类似:

struct Node
{
    int grade;
    struct Node *next;
};

int main() {

    struct Node *head = NULL;
    struct Node *temp;
    int data;

    while (1) 
    {
        printf("Enter the grade: \n ");
        if (scanf("%d", &data) != 1)
        {
            // Illegal input
            exit(1);
        }
        if (data == -1) break;  // Stop the loop

        temp = malloc(sizeof *temp);  // Allocate new element
        if (temp == NULL)
        {
            // Out of mem
            exit(1);
        }
        temp -> next = head;   // Insert new element in the front of list
        temp -> grade = data;
        head = temp;           // Move the front (aka head) to the new element
    }

    // .... add code that uses the list

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM