如何将下面的数组更改为包含结构和指针的双链接列表,并使此程序仍然有效?我想那是可能的,对吧?我需要创建的程序需要将名称和年龄存储到双链接列表中的节点中。
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#define SIZE 10
void input (char fullname[][25], int age[]);
void output (char fullname[][25], int age[]);
void bubblesortname (char fullname[][25], int *age, int size);
void bubblesortage (char fullname[][25], int *age, int size);
void fflush_stdin();
//Input function handles prompt and user input.
void input (char fullname[][25], int age[])
{
int i = 0;
size_t nchr = 0;
for (i = 0; i < SIZE; i++) {
printf ("\nEnter a full name: ");
if (fgets (fullname[i], 24, stdin) != NULL)
{
nchr = strlen (fullname[i]);
while (nchr > 0 && (fullname[i][nchr -1] == '\n' || fullname[i][nchr -1] == '\r'))
fullname[i][--nchr] = 0;
}
printf ("Enter the age : ");
scanf ("%d", &age[i]);
fflush_stdin();
}
}
//output function prints out name and age array
void output (char fullname[][25], int age[])
{
int i;
for (i = 0; i < SIZE; i++)
printf (" %-30s, %d\n", fullname[i], age[i]);
}
int main (void)
{
//array for user entered names
char fullname[SIZE][25];
//array for user enter ages
int age[SIZE];
// promt user for names and ages
input (fullname, age);
//output unsorted names and ages
output (fullname, age);
// sorts by name
bubblesortname (fullname, age, SIZE);
// output sorted names
output (fullname, age);
//sorts age
bubblesortage (fullname, age, SIZE);
//output sorted ages with corresponding names
output (fullname, age);
return 0;
}
// sorts the fullname array with bubblesort
void bubblesortname (char fullname[][25], int *age, int size)
{
int j = 0, i = 0;
int temp_age = 0;
char temp_name[25] = {0};
for (i = 0; i < size - 1; ++i) {
for (j = 0; j < size - 1 - i; ++j) {
if (strcmp (fullname[j], fullname[j + 1]) > 0) {
temp_age = age[j + 1];
age[j + 1] = age[j];
age[j] = temp_age;
strcpy (temp_name, fullname[j + 1]);
strcpy (fullname[j + 1], fullname[j]);
strcpy (fullname[j], temp_name);
}
}
}
}
//sorts age array
void bubblesortage (char fullname[][25], int *age, int size)
{
int j = 0, i = 0;
int temp_age = 0;
char temp_name[25] = {0};
for (i = 0; i < size - 1; ++i) {
for (j = 0; j < size - 1 - i; ++j) {
if (age[j] > age[j + 1]) {
temp_age = age[j + 1];
age[j + 1] = age[j];
age[j] = temp_age;
strcpy (temp_name, fullname[j + 1]);
strcpy (fullname[j + 1], fullname[j]);
strcpy (fullname[j], temp_name);
}
}
}
}
void fflush_stdin()
{ int c; while ((c = getchar()) != '\n' && c != EOF); }
最佳答案
目前还不清楚你的C级专长是什么。下面的一些是相当基本的,并不是所有的问题都包括在内。如有需要,请进一步询问。
大多数数据结构都会使用指针和Cstruct
结构。例如,在您的情况下,双链接列表节点可能如下所示:
struct person_node {
struct person_node *next;
struct person_node *prev;
char name[25];
int age;
};
/* This holds the start of the list */
struct person_node *list_head = NULL;
然后,您将拥有添加到列表、从列表中移除、搜索列表等功能。其中一些功能(至少添加和移除)将处理动态分配和释放节点,作为其操作的一部分。