如下是建立一个n个元素链表,数据有多组
输入x并删除与x值相除的所有结点,最后输出新的链表。
代码如下
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
void del(struct node * h, int x)
{
struct node * p, * q , * t;
p = h;
q = p->next;
if(h == NULL)
{
printf("链表为空\n");
exit(0);
}
while(q!= NULL)
{
if(q->data == x)
{
p->next = q->next;
free(q);
q = p->next;
}
else
{
p = p->next;
q = q->next;
}
}
if(h != NULL && h->data == x)
{
t = h;
h = h->next;
free(t);
}
}
int main()
{
int n,i,x;
while(scanf("%d",&n)!=-1)
{
struct node *h,*p,*q;
h=(struct node *)malloc(sizeof(struct node));
p=q=h;
for(i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
q->next=p;
q=p;
}
q->next=NULL;
p=h->next;
scanf("%d",&x);
del(h,x);
while(1)
{
if(p->next==NULL)
{
printf("%d\n",p->data);
break;
}
else
{
printf("%d ",p->data);
}
p=p->next;
}
free(p);
}
return 0;
}
目前问题是如果删除头节点直接崩,但是也判断了头结点啊,先把不是头结点删除再判断原来的,试了两天了
就是个实验小题,比较不解求解答