【发布时间】:2015-04-30 03:24:59
【问题描述】:
如何将以下数组更改为具有结构和指针的双向链表,并且该程序仍然可以工作?我认为这可能是正确的?我需要创建的程序需要将姓名和年龄存储到双向链表上的节点中。
#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); }
【问题讨论】:
-
这不是一个简单的问题,无需编写所有代码即可回答。你有更具体的问题吗?双链表有哪些你不明白的地方?
-
我真的只是开始喜欢如何将两个数组变成节点?我可能无法正确表达这一点... char fullname[][25], int age[] 如何删除这两个数组以允许用户将姓名和年龄存储到双向链表中?
-
你知道
struct怎么用吗?这就是您将用来定义列表节点的内容。
标签: c bubble-sort doubly-linked-list