首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

大家帮小弟我看看,这个删除链表节点的哪里出错了

2013-01-02 
大家帮我看看,这个删除链表节点的哪里出错了void delete_p(struct node *head,struct node *p){struct nod

大家帮我看看,这个删除链表节点的哪里出错了
void delete_p(struct node *head,struct node *p)
{
struct node *q;
if(p==NULL)
{
printf("no found\n");
return;
}
if(p==head)
{
head=p->next;
q=p;
}
else
{
q=p->next;
p->next=q->next;
}
printf("\ndelete :%d\n",q->data);
free(q);
}


[解决办法]


void delete_p(struct node *head,struct node *p)
{
   if(p==NULL)
  {
     printf("no found\n");
     return;
   }
   struct node *q = head;

   if(p==head)
   {
       head = head->next;
       q = p;
    }
    else
   {
       while (NULL != q ->next && q->next != p)
           q = q -> next;   //q指向下一个节点
      if (q ->next != NULL)   //找到了p节点
      {
          q->next=q->next->next;
          q = p;
      }
      else
      {
          return ;    //未找到
      }
    }
    printf("\ndelete :%d\n",q->data);
    free(q);
}


这是修改你的代码后的,没有测试。你可以使用你的代码测试一下,如果有问题我们可以在讨论一下

热点排行