单链表似乎不起作用

时间:2013-03-23 04:52:39

标签: 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是指向列表的指针。

2 个答案:

答案 0 :(得分:2)

您尚未为指针 pPre PList 指定NULL,请尝试以下代码,它运行O.K.现在,

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

答案 1 :(得分:0)

根据您的代码逻辑,您希望addNode()修改pPre。所以你需要将pPre定义为Node *的指针。

Node * addNode(Node *pList, Node **pPre, int data)

addNode()应该返回pList,你可能会错过它。