【问题标题】:How do you get a data section from a Linked list to compare?如何从链接列表中获取数据部分进行比较?
【发布时间】:2017-10-10 05:24:21
【问题描述】:

我刚刚开始学习链表并且正在搞乱它,但后来我遇到了一个问题。我不知道如何访问数据成员来实际比较它。在我的代码中,我提示用户输入成绩,当他们输入 -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;
        }
    }
}

【问题讨论】:

  • Sky,在学习链表(或几乎任何其他复杂结构)时,拿出一张 8.5x11 的纸和一支铅笔,然后画出将它们链接在一起的节点和节点指针。举个小例子,4-5个节点,然后计算出你adddelfind等。使用论文的函数供你参考,以获得正确的链接和循环。这比无休止地盯着屏幕寻找灵感所花费的时间要少得多:)

标签: c linked-list


【解决方案1】:

您的代码存在许多问题:

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;
}

【讨论】:

    猜你喜欢
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多