利用c语言里的链表删除大于k的节点,以0为结尾,输入k和链表,输出删除后的链表。(只会c语言,还没有学习c++)
不知道为什么代码运行错误,我是根据书上的链表删除的公式写的删除函数的,但是完全没发删除,感觉很苦恼
例子:
输入:2000
2001 2002 1999 1998 2021 1997 0
输出:1999 1998 1997
```c
#include<stdio.h>
#include<malloc.h>
struct cell
{
int year;
struct cell*next;
};
struct cell*build(void)
{
struct cell*head,*p,*tmp;
int n;
head=p=tmp=NULL;
scanf("%d",&n);
if(n==0)
{
return head;
}
p=(struct cell*)malloc(sizeof(struct cell));
p->year=n;
p->next =NULL;
head=p;
scanf("%d",&n);
while(n!=0)
{
tmp=(struct cell*)malloc(sizeof(struct cell));
tmp->year=n;
tmp->next=NULL;
p->next=tmp;
p=p->next;
scanf("%d",&n);
}
return head;
};
struct cell*delect(struct cell*head,int k)
{
struct cell*p,*p0,*p1;
p=head;
p0=NULL;
if(head==NULL){return head;}
while(p->year>k)
{p=p->next;free(p0->next);p0->next=p;
}
head=p;
while(p!=NULL)
{
if(p->year>k){p=p->next;free(p0->next);p0->next=p;}
p0=p;p=p->next;
}
return head;
};
void print(struct cell*head)
{
struct cell*p;
p=head;
if(head==NULL){printf("NULL");return;}
while(p!=NULL)
{
printf("%d",p->year);
if(p->next!=NULL){printf(" ");}
}
}
void release(struct cell*head)
{
struct cell*p0,*p;
p=head;
while(p!=NULL)
{
p0=p;p=p->next;free(p0);
}
}
int main()
{
struct cell*head;int k;
scanf("%d",&k);
head=build();
head=delect(head,k);
print(head);
release(head);
return 0;
}