gpt4 book ai didi

c - C 结构体中的反向输出顺序

转载 作者:行者123 更新时间:2023-11-30 19:15:46 24 4
gpt4 key购买 nike

我目前正在开发一个项目,但遇到了一些障碍。我已经完成了所需的代码,但是有一个额外的部分要求我以与当前相反的顺序打印输出。

例如:

21, Fred Nurk
927, Arwen Evensong

应该返回:

Arwen Evensong (927)
Fred Nurk (21)

但目前正在返回:

Fred Nurk (21)
Arwen Evensong (927)

我想知道是否有一种简单的方法可以在不更改太多代码的情况下做到这一点?抱歉,如果代码有点困惑且难以阅读,有一些限制使得这个问题写起来非常烦人:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAX_LINE_LENGTH 80
#define MAX_NUM_STUDENTS 500
#define MAX_NAME_SIZE 50

typedef struct student_s Student;

struct student_s {
int age;
char name[MAX_NAME_SIZE];
Student* next;
};

Student studentPool[MAX_NUM_STUDENTS];
int firstFree = 0;


Student* newStudent(const char* name, int age) {
Student* student = NULL;
if (firstFree < MAX_NUM_STUDENTS) {
student = &studentPool[firstFree];
firstFree += 1;
strncpy(student->name, name, MAX_NAME_SIZE);
student->name[MAX_NAME_SIZE - 1] = '\0';
student->age = age;
student->next = NULL;
}
return student;
}


Student* readOneStudent(FILE* file)
{
char *buffer;
buffer = (char *)malloc(MAX_LINE_LENGTH);
Student* student = NULL;
char* cp = fgets(buffer, MAX_LINE_LENGTH, file);
if (cp != NULL) {
char* commaPos = strchr(buffer, '\040');
int age = atoi(buffer);
if (commaPos != NULL && commaPos > buffer) {
*commaPos = '\0';
student = newStudent((commaPos+1),age);

}
}
return student;
}

Student* readStudents(FILE *file)
{
Student* first = NULL;
Student* last = NULL;
Student* student = readOneStudent(file);
while (student != NULL) {
if (first == NULL) {
first = last = student;
}
else {
last->next = student;
last = student;

}
student= readOneStudent(file);
}

return first;
}


void printOneStudent(Student student)
{

strtok(student.name, "\n");
if (student.name != '\0'){
printf("%s (%d)\n", student.name, student.age);
}
else{
printf("%s (%d)",student.name, student.age);
}
}


void printStudents(const Student* student)
{
while (student != NULL) {
printOneStudent(*student);
student = student->next;
}
}


int main(void)
{
FILE* inputFile = stdin;
if (inputFile == NULL) {
fprintf(stderr, "File not found\n");
}
else {
Student* studentList = readStudents(inputFile);
printStudents(studentList);
}
}

最佳答案

或者,您可以使用递归来反转单链表:

void printStudentsRev(const Student* student)
{
if (student != NULL) {
printStudentsRev(student->next);
printOneStudent(*student);
}
}

由于堆栈区域有限,这不适用于很长的列表

关于c - C 结构体中的反向输出顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31879896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com