C编程Listnode插入节点导致无限循环

标签 c loops pointers nodes infinite

在将节点插入 ListNode 时尝试进行双重引用时,我遇到了一些问题。这是代码:

#include "stdafx.h"
#include <stdlib.h>

typedef struct _listnode {
    int num;
    struct _listnode *next;
}ListNode;

void insertNode(ListNode **ptrHead, int index, int value);
ListNode *findNode(ListNode *head, int index);

int main()
{
    int index, value, i;
    ListNode **ptrHead, *head = NULL;

    ptrHead = &head;

    for (i = 0; i < 5; i++){
        printf("Enter value: ");
        scanf("%d", &value);
        printf("Enter index: ");
        scanf("%d", &index);

        insertNode(ptrHead, index, value);
    } 

    ptrHead = head;
    while (ptrHead != NULL) {
        printf("%d", head->num);
        ptrHead = head->next;
    }

    return 0;
}

void insertNode(ListNode **ptrHead, int index, int value) {
    ListNode *cur, *newNode;
    if (*ptrHead == NULL || index == 0) {
        newNode = malloc(sizeof(ListNode));
        newNode->num = value;
        newNode->next = *ptrHead;
        *ptrHead = newNode;
    }
    else if ((cur = findNode(*ptrHead, index - 1)) != NULL) {
        newNode = malloc(sizeof(ListNode));
        newNode->num = value;
        newNode->next = cur->next;
        cur->next = newNode;
    }
    else printf("Cannot insert the new item at index %d!\n", index);
}

ListNode *findNode(ListNode *head, int index) {
    ListNode *cur = head;
    if (head == NULL || index < 0)
        return NULL;
    while (index > 0) {
        cur = cur->next;
        if (cur == NULL) return NULL;
        index--;
    }
    return cur;
}

所以基本上我从用户那里获取 5 个值和索引输入。然后,我将它们插入到 ListNode 中。在 insertNode() 内部,有一个名为 findNode 的函数,它试图找到 cur,以便我可以将我的 cur 指向下一个 新节点

但是,使用这些代码,当我尝试打印 ListNode 时,它会无限打印出第一个输入值。所以我在想我的错误是哪一部分?

提前致谢。

最佳答案

在您的 main 函数中,包含以下代码行:

ptrHead = head;
while (ptrHead != NULL) {
    printf("%d", head->num);
    ptrHead = head->next;
}

应为:

ListNode *cur = head;
while (cur != NULL) {
    printf("%d", cur->num);
    cur = cur->next;
}

编辑:

But can I know why it does not work when I assign head to ptrHead. Is it because I am double deferencing the ptrHead?

它们有不同的类型。 ptrHeadListNode**,而 headListNode*。因此,赋值 ptrHead = head; 不会做你真正想要的事情。此外,现代编译器应该在这一行发出一些警告。

关于C编程Listnode插入节点导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33185980/

相关文章:

c - 程序演示文件IO操作

c - 如何在 C 中按字典顺序对二维字符数组进行排序?

c - 尝试计算字符串中逗号的数量并保存到 int 计数器

c++ - 不明白C++中的strcpy

c - 使用不同的参数运行不同的函数 - 函数指针

c - 声明指向指向指针的指针

c - 为什么参数类型不正确(应该是 int * 的时候是 int)?

C for循环继续递增

c - 在循环中使用 2 个变量对数组求和(并运行循环 N/2 次)比仅使用一个变量的运行时间更快。为什么?

c - 忽略来自标准输入的退格键