描述
输入
输入包含3行:
第一行是一个整数n(1 <= n <= 200000),代表数组中元素的个数。
第二行包含n个整数,代表数组中的n个元素。每个整数之间用空格分隔;每个整数的取值在32位有符号整数范围以内。
第三行是一个整数k,代表待删除元素的值(k的取值也在32位有符号整数范围内)。
输出
输出只有1行:
将数组内所有待删除元素删除以后,输出数组内的剩余元素的值,每个整数之间用空格分隔。
样例输入
样例输出
给定N个整数,将这些整数中与M相等的删除
假定给出的整数序列为:1,3,3,0,-3,5,6,8,3,10,22,-1,3,5,11,20,100,3,9,3
应该将其放在一个链表中,链表长度为20
要删除的数是3,删除以后,链表中只剩14个元素:1 0 -3 5 6 8 10 22 -1 5 11 20 100 9
要求:必须使用链表,不允许使用数组,也不允许不删除元素直接输出
程序中必须有链表的相关操作:建立链表,删除元素,输出删除后链表中元素,释放链表
不符合要求的程序即使通过,也会算作0分
第一行是一个整数n(1 <= n <= 200000),代表数组中元素的个数。
第二行包含n个整数,代表数组中的n个元素。每个整数之间用空格分隔;每个整数的取值在32位有符号整数范围以内。
第三行是一个整数k,代表待删除元素的值(k的取值也在32位有符号整数范围内)。
将数组内所有待删除元素删除以后,输出数组内的剩余元素的值,每个整数之间用空格分隔。
20 1 3 3 0 -3 5 6 8 3 10 22 -1 3 5 11 20 100 3 9 3 3
1 0 -3 5 6 8 10 22 -1 5 11 20 100 9
#include<stdio.h> struct stu { int num; struct stu *next; }; void creat(struct stu *head,int i) { struct stu *p; head->next=NULL; while(i--) { p=new stu; scanf("%d",&p->num); p->next=head->next; head->next=p; head=p; } } void dele(struct stu *head,int k) { struct stu *p=head; head=head->next; while(head!=NULL) { if(head->num==k) { p->next=head->next; head=p->next; } else { p=p->next; head=head->next; } } } void print(struct stu *head) { head=head->next; while(head!=NULL) { printf("%d ",head->num); head=head->next; } printf("\n"); } int main() { int n; int k; stu *head=new stu; scanf("%d",&n); creat(head,n); scanf("%d",&k); dele(head,k); print(head); return 0; }
另一种方法
<pre name="code" class="cpp">#include<stdio.h> #include<malloc.h> #define LEN sizeof(struct data) struct data { int num; struct data *next; }; struct data* creat(int n)//创建链表 { struct data *p1,*p2,*head; int i=0; p1=head=NULL; while(n--) { i++; p1=(struct data*)malloc(LEN); if(i==1) head=p1;//如果是第一个结点,使head=p1,让head指向新开辟的结点 else p2->next=p1;//如果不是,令p2指向前一个结点,新结点地址赋给上一个的next p2=p1;//使p2指向新建立的结点 scanf("%d",&p1->num); } p2->next=NULL; return head; } struct data * del(int k,struct data *head)//删除节点 { struct data *p1,*p2; for(p2=p1=head;p1!=NULL;) { if(p1->num==k) { if(p1==head) { head=p1->next; free(p1);//l若p1指向首结点,将第二个结点地址赋给head } else { p2->next=p1->next; free(p1);//若不是就将下一结点的地址赋给前一结点地址 p1=p2->next; } } else { p2=p1; p1=p1->next; } } return head; } int main() { int n,k; struct data *p; scanf("%d",&n); p=creat(n); scanf("%d",&k); p=del(k,p); if(p!=NULL) { while(p->next!=NULL) { printf("%d ",p->num); p=p->next; } printf("%d\n",p->num); } return 0; }