在C语言中实现双链表(删除任意位置的节点)
我有这个函数,可以删除双链表中任意位置的节点。如果您只有一个节点,则工作正常。我尝试插入3个节点,然后删除最后一个,它只是冻结 以下是我使用的函数:在C语言中实现双链表(删除任意位置的节点),c,doubly-linked-list,C,Doubly Linked List,我有这个函数,可以删除双链表中任意位置的节点。如果您只有一个节点,则工作正常。我尝试插入3个节点,然后删除最后一个,它只是冻结 以下是我使用的函数: int getpos(char ln[20]) { int pos=1; temp3=h; if(temp3 == NULL) { printf("List empty"); return; } while(temp3->
int getpos(char ln[20])
{
int pos=1;
temp3=h;
if(temp3 == NULL)
{
printf("List empty");
return;
}
while(temp3->next!=NULL)
{
if(strcmp(temp3->lname,ln)==0)
{
break;
}
else
{
pos++;
}
}
return pos;
}
获取要删除的节点位置的函数
void del()
{
int i = 1, pos=0;
char ln[20];
temp2 = h;
printf("enter lname: ");
gets(ln);
pos=getpos(ln);
if ((pos < 1) || (pos >= count + 1))
{
printf("\n Error : Position out of range to delete");
return;
}
if (h == NULL)
{
printf("\n Error : Empty list no elements to delete");
return;
}
else
{
while (i < pos)
{
temp2 = temp2->next;
i++;
}
if (i == 1)
{
if (temp2->next == NULL)
{
printf("Node deleted from list");
free(temp2);
temp2 = h = NULL;
return;
}
}
if (temp2->next == NULL)
{
temp2->prev->next = NULL;
free(temp2);
printf("Node deleted from list");
return;
}
temp2->next->prev = temp2->prev;
if (i != 1)
temp2->prev->next = temp2->next; /* Might not need this statement if i == 1 check */
if (i == 1)
h = temp2->next;
printf("\n Node deleted");
free(temp2);
}
count--;
}
void del()
{
int i=1,pos=0;
char-ln[20];
temp2=h;
printf(“输入lname:”);
获取(ln);
pos=getpos(ln);
如果((位置<1)| |(位置>=计数+1))
{
printf(“\n错误:位置超出要删除的范围”);
返回;
}
if(h==NULL)
{
printf(“\n错误:空列表没有要删除的元素”);
返回;
}
其他的
{
while(inext;
i++;
}
如果(i==1)
{
如果(temp2->next==NULL)
{
printf(“从列表中删除的节点”);
免费(临时2);
temp2=h=NULL;
返回;
}
}
如果(temp2->next==NULL)
{
temp2->prev->next=NULL;
免费(临时2);
printf(“从列表中删除的节点”);
返回;
}
temp2->next->prev=temp2->prev;
如果(i!=1)
temp2->prev->next=temp2->next;/*如果i==1检查,则可能不需要此语句*/
如果(i==1)
h=temp2->next;
printf(“\n节点已删除”);
免费(临时2);
}
计数--;
}
删除节点的函数。在函数
getpos
中,您没有递增temp3->next
,因此while
循环将永远运行
顺便说一句,一次简单的调试尝试就可以省去你问这个问题的麻烦。你可以这样写:
void delete_node(Node* pNode)
{
pNode->Data = pNode->Next->Data;
pNode->Next->Next->Previous = pNode;
Node* pTemp = pNode->Next;
delete(pNode->Next);
pNode->Next = pTemp;
}
这个函数。只处理中间节点,
因此,只要确保添加边缘案例-如果节点是第一个或最后一个。请阅读指南。在发布关于代码的问题之前,先把它缩小到最小但完整的例子。你可能想尝试这里描述的方法来解决这个问题。考虑使用哨兵节点。看看