我的数据结构类有问题。我的任务是生成 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;
}