对列表元素进行分类后加标签存入字典题目要求:输入一个列表,要求列表中的每个元素都为正整数且列表包含的元素个数为偶数;将列表中前一半元素保存至字典的第一个键值1中,后一半元素保存在第二个键值2中。输入样例:1234输出样例:‘1:[1,2],‘2*:[3,4])
稍等,帮你写一个
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
struct Dict {
int key;
int* value;
};
int main() {
int n;
printf("请输入列表的长度(必须为偶数):");
scanf("%d", &n);
if (n % 2 != 0) {
printf("列表长度必须为偶数!\n");
return 1;
}
int* list = malloc(n * sizeof(int));
printf("请输入列表的元素(用空格分隔):");
for (int i = 0; i < n; i++) {
scanf("%d", &list[i]);
}
struct Dict dict;
dict.key = 1;
dict.value = malloc((n / 2) * sizeof(int));
for (int i = 0; i < n / 2; i++) {
dict.value[i] = list[i];
}
printf("'1:[");
for (int i = 0; i < n / 2; i++) {
printf("%d", dict.value[i]);
if (i != n / 2 - 1) {
printf(",");
}
}
printf("],'");
dict.key = 2;
dict.value = malloc((n / 2) * sizeof(int));
for (int i = 0; i < n / 2; i++) {
dict.value[i] = list[i + n / 2];
}
printf("'2':[");
for (int i = 0; i < n / 2; i++) {
printf("%d", dict.value[i]);
if (i != n / 2 - 1) {
printf(",");
}
}
printf("]')\n");
free(list);
free(dict.value);
return 0;
}
先进后出(后进先出)