【发布时间】:2021-10-31 09:15:22
【问题描述】:
我的数据结构类有问题。我的任务是生成 30 个随机数,然后按生成顺序将它们打印到列表中。之后,我必须从列表中删除可被 3 整除的数字和包含数字“3”的数字。最后,我需要按升序将该列表打印到文件中,但我们不允许在打印到文件之前对列表进行排序。
我的代码工作正常,但我找不到按升序将数字打印到文件的解决方案。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
#include<stdbool.h>
#define BUFFER_LENGTH 256
typedef struct lista* Poz;
typedef struct lista {
int br;
Poz next;
}lista;
bool containsDigit(int, int);
int PrintList(Poz);
int PrintRandom(int, int);
Poz StvoriCvor();
int PrintToFile(Poz);
bool containsDigit(int number, int digit) {
while (number != 0) {
int curr_digit = number % 10;
if (curr_digit == digit)
return true;
number /= 10;
}
return false ;
}
int PrintToFile(Poz P) {
int digit = 3;
if (P == NULL) return -1;
Poz temp;
temp = StvoriCvor();
if (temp == NULL) return -1;
char* fileName = NULL;
FILE* fp;
fileName = (char*)malloc(sizeof(char) * BUFFER_LENGTH);
if (fileName == NULL) return -1;
printf("Unesite ime datoteke:\n");
scanf("%s", fileName);
fp = fopen(fileName, "w+");
if (fp == NULL) return -1;
while (P != NULL) {
if (P->br % 3 == 0 || containsDigit(P->br, digit) == true) {
P = P->next;
}
else {
fprintf(fp, "%d\n", (int)P->br);
P = P->next;
}
}
fclose(fp);
return 0;
}
int PrintRandom(int min, int max) {
int num = (rand() % (max - min + 1) + min);
return num;
}
int PrintList(Poz P) {
P = P->next;
if (P == NULL) {
printf("Lista je prazna.\n");
}
else {
printf("Sljedeci brojevi su u listi.\n");
while (P != NULL) {
printf("%d ", P->br);
P = P->next;
}
}
return 0;
}
Poz StvoriCvor() {
Poz Q = NULL;
Q = (Poz)malloc(sizeof(lista));
if (Q == NULL) {
printf("Greska u funkciji StvoriCvor.\n");
}
Q->next = NULL;
return Q;
}
int main() {
Poz Sort = NULL;
lista head;
head.next = NULL;
Poz Q = NULL;
Poz temp = NULL;
int min = 0, max = 100, count = 30;
srand(time(0));
int pr = 100, x = 0;
char* choice;
choice = (char*)malloc(sizeof(char));
if (choice == NULL) {
printf("Greska.\n");
}
for (int i = 0; i < count; i++) {
Q = StvoriCvor();
if (Q == NULL) {
printf("Greska u funkciji StvoriCvor.\n");
}
else {
Q->br = PrintRandom(min, max);
Q->next = head.next;
head.next = Q;
}
}
PrintList(&head);
PrintToFile(head.next);
return 0;
}
【问题讨论】:
-
如果您不允许对列表进行排序,则只需遍历整个列表,每次查找并删除最小值。也就是说,将 min 设置为第一个元素,然后检查下一个元素,如果它小于 min,则将其设置为新的 min 并继续对列表的其余部分进行操作。
-
看来你失败了
delete numbers divisible by 3 and numbers that contain digit ‘3’ from the list.;您只需在打印时跳过它们... -
如果这是一个数据结构类,也许你应该考虑使用更合适的数据结构。
-
例如,遍历列表一次,然后将每个元素推送到支持有序遍历的不同数据结构中。
-
"最后我需要按升序将该列表打印到文件中。但是我们不允许在打印到文件之前对列表进行排序。"这不矛盾吗?