微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

虽然循环没有到达链表的末尾

如何解决虽然循环没有到达链表的末尾

我正在学习数据结构,并且正在尝试创建一个链表。我的问题是我的两个 while 循环中的一个没有到达链表的末尾(它在第一个元素处停止)。它们并不完全相等,但非常相似;第一个循环(工作循环)在当前列表指针不为空时运行,第二个在下一个列表指针不为空时运行。编译器没有显示任何错误,程序在打开时也不会停止工作。同样重要的是,这不是我的主要代码,它是我编写的测试代码,试图自己解决问题(不幸的是,没有成功) - 但它有助于说明问题。

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

typedef struct List {
    int data;
    struct List *next;
} List;

int main(void) {
    system("cls");

    List *hook    = (List *) malloc(sizeof(List)),*root1   = (List *) malloc(sizeof(List)),*root2   = (List *) malloc(sizeof(List)),*root3   = (List *) malloc(sizeof(List)),*item    = (List *) malloc(sizeof(List)),*current = (List *) malloc(sizeof(List));

    hook->data = -20;
    hook->next = root1;

    root1->data = 10;
    root1->next = root2;

    root2->data = 20;
    root2->next = root3;

    root3->data = 30;
    root3->next = NULL;

    current = hook;
    while (current != NULL) {
        printf("\"First while\" data: %i\n",current->data);
        current = current->next;
    }
    // In this while cycle,the code goes through all the items of the linked list and print their data values correctly

    printf("\"Hook\" next: %i\n",hook->next);
    current = hook;

    printf("\"Current->next\" next: %i\n",current->next->next);

    while (current->next != NULL) {
        current->next = current->next->next;
    }
    // On the other hand,in this while cycle the code stops in the first element of the list (hook);
    // consequently,it prints the first data value,but the intention was to get in the end of the list and print the last value

    printf("\"Second while\" data: %i\n",current->data);
    
    return 0;
}

Picture of the terminal with the program output

“Hook”和“Current->next”故意与“%i”一起显示,只是为了验证它们是否不为空。我到底做错了什么?

解决方法

带循环

while (current->next != NULL) {
    current->next = current->next->next;
}

修改列表,有效地从列表中删除除第一个节点之外的所有节点。

如果你只想迭代它以获得最后一个节点,你需要像往常一样更新current

while (current->next != NULL) {
    current = current->next;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。