题目
答案
struct ListNode *readlist()
{
int n;
scanf("%d",&n);
if(n==1) return NULL;
struct ListNode *head,*p,*temp;
head=(struct ListNode *)malloc(sizeof(struct ListNode));
head->data=n;
head->next=NULL;
p=head;
scanf("%d",&n);
while(n!=-1)
{
temp=(struct ListNode *)malloc(sizeof(struct ListNode));
temp->data=n;
temp->next=NULL;
p->next=temp;
p=p->next;
scanf("%d",&n);
}
return head;
}
struct ListNode *deletem( struct ListNode *L, int m )
{
struct ListNode *head,*p;
head=(struct ListNode *)malloc(sizeof(struct ListNode *));
head->next=L;
p=head;
while(p->next)
{
if(p->next->data==m)
{
p->next=p->next->next;
}
else p=p->next;
}
return head->next;
}
测试点
思路
1.在删除节点时我选择创立一个head作为L的头结点,这样就不需要对L进行分类讨论了,只需在最后返回head->next即可
2.else p=p->next;
这个地方一定要加else,因为在删除节点后p的位置是不能改变的,不然会跳过还没判断的数据。