【发布时间】:2015-04-16 19:39:21
【问题描述】:
我已经开始学习链接列表,通过视频和多个示例,我已经非常了解链接列表是什么以及它如何在现实生活中进行类比。但是当涉及到编码时,我会迷失方向,我想通过所有我有点困惑的指针,我花了一些时间来更好地掌握数组,所以我认为它与链接列表相同。所以这是我的代码
/*
• The program will use dynamic memory to create a singly linked list(NO ARRAYS PERMITTED)
• The program will store unlimited number of student records(limited only by RAM).
• A student record will consist of Student Name, Age, and GPA…you may need to add additional fields to make this work(Next).
• The program will have a way for the user to add records(in order by name).You can assume that no two students have the same name.The list will always be in order.
• The program will have a way for the user to display ALL records.
• The program needs a way to quit.
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#pragma warning(disable: 4996)// disables warning
typedef struct{
char name[40];
int age;
float gpa;
struct NODE* next;
}NODE;
void addStudent();
int main(void){
NODE* head = NULL;
int userinput;
printf(" **********************************\n");
printf(" * MENU *\n");
printf(" * 1. Add Student *\n");
printf(" * 2. Display all student records*\n");
printf(" * 3. Quit *\n");
printf(" **********************************\n");
scanf_s("%d%*[^\n]", &userinput); '\n' == getchar();
switch (userinput)
{
case 1: do
{
addStudent(head);
printf("Add another record? 1(y) 2(n)\n");
scanf_s("%d%*[^\n]", &userinput); '\n' == getchar();
} while (userinput == 1);
break;
}
}
void addStudent(NODE* head){
head = malloc(sizeof(NODE));
if (head == NULL)
{
return;
}
NODE * current = head;
printf("Please Enter student name:\n");
fgets(current->name, 40, stdin);
printf("Enter student age:\n");
scanf("%d%*[^\n]", ¤t->age); '\n' == getchar();
printf("Enter student gpa:\n");
scanf("%f%*[^\n]", ¤t->gpa); '\n' == getchar();
current->next;
current->next = NULL;
while (current != NULL){
current = head;
printf("%s\n", current->name);
printf("%d\n", current->age);
printf("%0.2f\n", current->gpa);
current = current->next;
}
}
当我编译时,它总是会打印我认为它的头部,因为 current = head 在 while 循环中,我理解为什么它打印头部但我不知道如何安排这段代码这样我就可以创建一个当我通过循环添加和打印所有节点时的新节点。
【问题讨论】:
标签: c arrays data-structures linked-list