c语言 删除链表的某个节点

//删除p指向的节点
int delNode(stuInfo*p)
{
stuInfo*temp;
temp=p;
p=p->next;
temp->next=NULL;
free(temp);
return 0;
}

有错误吗?我只要求删除p指向的节点,其余无要求。
//删除p指向的节点
stuInfo*delNode(stuInfo*head,stuInfo*p)
{
stuInfo*temp,*q;
q=initialize(q);
q->next=head;
temp=p;
p=p->next;
temp->next=NULL;
free(temp);
head=q->next;
q->next=NULL;
free(q);
return head;
}

这是我修改后的,好像还是不对。。真不明白。。。

temp=p;
p=p->next;
temp->next=NULL;
这三句存在问题,temp=p,让temp指向p所指向的节点,p=p->next,p指向后移
temp->next=NULL,让temp的后继为空,这里出了问题,链表从temp指向的节点断开,相当于删除p之后的所有节点。

应该先判断p是不是最后节点
if(p->next==NULL)
如果是,只好去找p的前趋pre,让pre->next=NULL,free(p)
如果不是最后节点,将p的后继节点数值域复制给p,然后将p的后继节点删除,等同与删除p
p->data=p->next->data;
p->next=p->next->next;
free(p);
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-07-03
p 的上一个节点要等于 p->next
struct node *delet(head,pstr)以/*he a d 为头指针,删除ps t r 所在节点*/
struct node *head;
char *pstr;
{
struct node *temp,*p;
t e m p = h e a d ; / * 链表的头指针* /
if (head==NULL) / *链表为空* /
printf("\nList is null!\n");
else /*非空表* /
{
t e m p = h e a d ;
while (strcmp(temp->str,pstr)!=0&&temp->next!=NULL)
/ * 若节点的字符串与输入字符串不同,并且未到链表尾* /
{
p = t e m p ;
t e m p = t e m p - > n e x t ; / * 跟踪链表的增长,即指针后移* /
}
if(strcmp(temp->str,pstr)==0 ) / *找到字符串* /
{
if(temp==head) { / * 表头节点* /
printf("delete string :%s\n",temp->str);
h e a d = h e a d - > n e x t ;
f r e e ( t e m p ) ; / *释放被删节点* /
}
e l s e
{
p->next=temp->next; /表*中节点*/
printf("delete string :%s\n",temp->str);
f r e e ( t e m p ) ;
}
}
else printf("\nno find string!\n");没/找* 到要删除的字符串*/
}
r e t u r n ( h e a d ) ; / *返回表头指针* /
}
第2个回答  2011-07-05
NODE * x = head; NODE * y = 0;
int i = 0;
for(i = 0; i < 8; i++) x = x->next;
y = x->next;
x->next = y->next;
free(y);
另外,站长团上有产品团购,便宜有保证