如何将下面的数组更改为带有结构和指针的双向链表,并且仍然让这个程序工作?我想这是可能的,对吗?我需要创建的程序需要将名称和年龄存储到双向链表上的节点中。
#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, %dn", 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 级专业知识是什么。以下一些是相当基本的,并非所有问题都涵盖。如有需要,请进一步询问。
大多数数据结构将使用指针和 C struct
构造。例如,在您的案例中,双向链表节点如下所示:
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;
然后,您将具有要添加到列表,从列表中删除,搜索列表等的功能。其中一些函数(至少添加和删除)将处理动态分配和释放节点作为其操作的一部分。