c - 单链表似乎不起作用

标签 c list linked-list

我正在尝试使用链接列表来适应它,但我无法使这个小程序工作。我不知道这里出了什么问题,请帮忙。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//Struct
struct Node {
    int value;
    struct Node *next;
};
typedef struct Node NODE;

//Function Declaration
NODE* addNode (NODE* pList, NODE* pPre, int data);
void printList (NODE* pList);

int main (void)
{
    //Local Declaration
    NODE *pPre;
    NODE *pList;

    //Statement
    pList = addNode (pList, pPre, 10);
    pList = addNode (pList, pPre, 20);
    pList = addNode (pList, pPre, 30);

    printList (pList);
    return 0;
}

NODE* addNode (NODE* pList, NODE* pPre, int data)
{
    //Local Declaration
    NODE* pNew;

    //Statement
    if (!(pNew = (NODE*)malloc(sizeof(NODE))))
    {
        printf("\aMemory overflow in insert\n");
        exit(1);
    }

    pNew->value = data;
    if (pPre == NULL)
    {
        //Inserting before first node or to empty list.
        pNew->next = pList;
        pList = pNew;
    }
    else
    {
        pNew->next = pPre->next;
        pPre->next = pNew;
    }
    return pList;
}
void printList (NODE* pList)
{
    //Local Declaration
    NODE* pNew;

    //Statement

    pNew = pList;
    while(pNew)
    {
        printf("%d", pNew->value);
        pNew = pNew->next;

    }
    return;
}

pPre是前驱节点,pList是指向链表的指针。

最佳答案

您尚未将 NULL 赋给指针 pPrePList,请尝试以下代码,它运行正常。现在,

NODE *pPre=NULL;
NODE *pList=NULL;

关于c - 单链表似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15583498/

相关文章:

linked-list - 展开的链表如何工作

c - 为什么 yacc 在退出时有内存泄漏?

c - 数组初始化的奇怪值

C程序导致内存泄漏?

java - 表达非法开始 NB

python - 在两个整数列表之间连续选择较大的数字

mysql - C程序mysql连接

r - 如何使用 mapply 复制嵌套 for 循环?

java - 双向链表空指针异常

c++ - 由带节点的链表组成的类似 STL 的列表