从链接列表中删除第一个节点后,结果不正确

时间:2014-01-19 23:37:50

标签: c linked-list

我写了这段代码来删除单链表中的第一个节点。

CreateLinkedList(node **headPtr)
{
    int i;
    node *pMyNode;
    pMyNode = (node*)malloc(sizeof(node)); //create space for first node []
    *headPtr=pMyNode;
    for(i=0;i<10;i++)
    {
        pMyNode->element = i; //enter value [0]
        printf("Value is %d addr is %p\n",pMyNode->element,pMyNode);
        pMyNode->nextPtr = (node*)malloc(sizeof(node)); //[0]->[]->NULL
        pMyNode = pMyNode->nextPtr;
    }
    pMyNode->nextPtr=NULL;
}

void PrintLinkedList(node **headPtr)
{
    node *pMyNode;
    int i;
    pMyNode=*headPtr;
    while(pMyNode)
    {
        printf("Value is %d addr is %p\n",pMyNode->element,pMyNode);
        pMyNode = pMyNode->nextPtr;
    }
}

void DeleteANode(node **headPtr)
{
    node *pMyNode; //head->[]->[]->[]->NULL
    pMyNode=*headPtr;
    *headPtr=*headPtr->nextPtr;
    free(pMyNode);

}
int main()
{   
    node *pNode;
    CreateLinkedList(&pNode);
    DeleteANode(&pNode);
    PrintLinkedList(&pNode);
}

我得到的输出是:

删除前

value is 0 addr is 8e75008 
value is 1 addr is 8e75018
value is 2 addr is 8e75028
value is 3 addr is 8e75038
value is 4 addr is 8e75048
value is 5 addr is 8e75058
value is 6 addr is 8e75068
value is 7 addr is 8e75078
value is 8 addr is 8e75088
value is 9 addr is 8e75098

删除后

value is 0 addr is 8e75008 // This node should not be printed
value is 0 addr is 8e75018 
value is 2 addr is 8e75028
value is 3 addr is 8e75038
value is 4 addr is 8e75048
value is 5 addr is 8e75058
value is 6 addr is 8e75068
value is 7 addr is 8e75078
value is 8 addr is 8e75088
value is 9 addr is 8e75098

2 个答案:

答案 0 :(得分:1)

您的一个问题是以下声明:

*headPtr=*headPtr->nextPtr;

->的优先级高于*,因此首先进行评估。要首先取消引用指针,您需要括号:

*headPtr=(*headPtr)->nextPtr;

另一个问题是以下块:

pMyNode=*headPtr;
for(i=0;i<10;i++)
{
    printf("Value is %d addr is %p\n",pMyNode->element,pMyNode);
    pMyNode = pMyNode->nextPtr;
}

您不应该硬编码有多少链接。而是使用while循环并检查NULL

pMyNode=*headPtr;
while(pMyNode)
{
    printf("Value is %d addr is %p\n",pMyNode->element,pMyNode);
    pMyNode = pMyNode->nextPtr;
}

答案 1 :(得分:1)

您的问题出在DeleteANode的这一行:*headPtr=*headPtr->nextPtr;

我认为它应该是*headPtr=(*headPtr)->nextPtr;

我不确定为什么你的版本不会在线上抛出错误/警告。 * headPtr的赋值应该是期望另一个指向节点的指针,你正在取消引用headPtr-&gt; nextPtr,从而尝试将节点结构分配给* headPtr?!