编程实现:输入一个正整数 repeat (0<repeat<10),做 repeat 次下列运算: 输入一个正整数 n(0<n<=9)和一组(n个)整数,建立一个单向链表,再输入一个整数 x,将链表中最后一个与x相等的整数删除。
输入:
3 (repeat=3)
5 (数据的个数n=5)
1 2 4 3 7 (5个整数)
4 (待删除整数x=4)
5 (数据的个数n=5)
2 1 5 7 5 (5个整数)
5 (待删除整数x=5)
3 (数据的个数n=3)
1 2 4 (3个整数)
100 (待删除整数x=100)
输出:
size=4:1 2 3 7
size=4:2 1 5 7
size=3:1 2 4
# include <stdio.h>
# include <stdlib.h>
typedef struct biao * list;
struct biao{
int data;
struct biao * next;
};
list create666(int n){ //尾结点链表创建
list head = NULL,p = NULL,tail=NULL;
for(int i=1;i<=n;i++){
p=(list)malloc(sizeof(struct biao));
scanf("%d",&p->data);
p->next=NULL;
if(head==NULL)
head=p;
else
tail->next=p;
tail=p;
}
return head;
}
void delete_print(list head,int n){ //删除与输出函数
list p1=NULL,p2=NULL,w=NULL; //此处置应删除节点为空
int x;
scanf("%d",&x);
p1=head;
while(p1){ //要删除的最后一个节点的查找
if(p1->data==x)
w=p1;
p1=p1->next;
}
if(w!=NULL){ // 第一部分 w不为空 说明已找到 size为n-1
printf("size=%d:",n-1);
if(w!=head){ //w不为头结点
p1=head;
while(p1->next!=w) //while只有1句 遍历w之前节点
p1=p1->next;
p1->next=w->next; //删除
free(w);
p2=head; //输出开始
while(p2->next!=NULL){
printf("%d ",p2->data);
p2=p2->next;
}
printf("%d\n",p2->data); //最后一个要求换行 单独输出
}
else{ //w为头结点
p1=head->next; //头结点后移
head=head->next;
free(p1);
p2=head; //输出头结点后所有的data
while(p2->next!=NULL){
printf("%d ",p2->data);
p2=p2->next;
}
printf("%d\n",p2->data);
}
}
else{ //第二部分 w为空 未找到 直接输出n个
printf("size=%d:",n);
p2=head;
while(p2->next!=NULL){
printf("%d ",p2->data);
p2=p2->next;
}
printf("%d\n",p2->data);
}
}
int main (){
int repeat;
scanf("%d",&repeat);
for(int i=1;i<=repeat;i++){
int n;
scanf("%d",&n);
list head=create666(n);
delete_print(head,n);
}
return 0;
}