6378:删除数组中的元素(链表)
总时间限制:
1000ms
内存限制:
65536kB
描述
给定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分
输入
输入包含3行:
第一行是一个整数n(1 <= n <= 200000),代表数组中元素的个数。
第二行包含n个整数,代表数组中的n个元素。每个整数之间用空格分隔;每个整数的取值在32位有符号整数范围以内。
第三行是一个整数k,代表待删除元素的值(k的取值也在32位有符号整数范围内)。
输出
输出只有1行:
将数组内所有待删除元素删除以后,输出数组内的剩余元素的值,每个整数之间用空格分隔。
样例输入
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<cstdio>
#include<iostream>
using namespace std;
#include<stdlib.h>
struct node {
int a;
node* next;
};
void delect(node* p, int c) {
node* q=p->next;
while(q!=NULL){
if(q->a==c){
p->next=q->next;
q=q->next;
}
else{
p=q;
q=q->next;
}
}
}
// node* d = (node*)malloc(sizeof(node));
// while (p->next != NULL) {
// if (p->next->next == NULL) {
// d = p;
// }
// if (p->next->a == c) {
// node* a1 = p;
// node* b1 = p->next->next;
// free(p->next);
// a1->next == b1;
// p = b1;
// }
// else {
// p = p->next;
// }
// }
// if (p->a == c) {
// d = NULL;
// }
//}
int main(){
int n;
cin >> n;
int num;
node* p = (node*)malloc(sizeof(node));
node* head = p;
p->next=(node*)malloc(sizeof(node));
p=p->next;
for (int i = 1; i <= n; i++) {
cin >> num;
if (i != n) {
p->next = (node*)malloc(sizeof(node));
p->a = num;
p = p->next;
}
else {
p->next = (node*)malloc(sizeof(node));
p->a = num;
p->next = NULL;
}
}
int c;
cin >> c;
delect(head, c);
while (head->next != NULL) {
printf("%d ", head->next->a);
head = head->next;
}
return 0;
}