[英]Incorrect result after removing first node from 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
您的问题之一是以下声明:
*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;
}
您的问题在DeleteANode的这一行中: *headPtr=*headPtr->nextPtr;
我相信应该是*headPtr=(*headPtr)->nextPtr;
我不确定为什么您的版本不会像您所看到的那样在网上抛出错误/警告。 * headPtr的分配应该期望有另一个指向节点的指针,并且您正在取消引用headPtr-> nextPtr,从而尝试将节点结构分配给* headPtr ?!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.