【发布时间】:2018-06-12 10:42:59
【问题描述】:
我正在尝试创建学生及其 ID 的链接列表。 我认为一切都很好,除了函数中的 List* 头。 我不擅长函数所以我不知道它是否正确。
当我尝试打印所有学生时,它没有给出任何输出,它只是返回到指令(再次通过主循环而不打印名称)。 你能帮帮我吗?
在我看来,头部在每个功能和主要功能中都没有保持相同,因此不会发生打印,但我不知道如何解决这个问题。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
typedef struct node
{
char name[50];
int ID;
node *next;
}
List;
void Linked_insert(char givenname[50], int givenID, int start, List* head)
{
//if its the users first time inserting start becomes 0 and if it isnt start is 1 so for both cases i made that condition
if(start==0){
strcpy(head->name, givenname);
head->ID = givenID;
head->next = NULL;
return head;
}
if(start==1){
//end of list
List* current = head;
while(current->next != NULL){
current = current->next;
}
current->next = malloc(sizeof(List));
strcpy(current->next->name, givenname);
current->next->ID = givenID;
current->next->next = NULL;
return current->next;
}
}
void Linked_destroy()
{
}
void Print_student(List* head)
{
}
void Print_all(List* head)
{
List* current = head;
while(current->next != NULL){
printf("Student ID [%d] has name [%s]\n", current->ID, current->name);
current = current->next;
}
}
int main()
{
int loop=0, start=0;
while(loop != 1)
{
printf("\n\n\n\n");
printf("Data Structures - Linked List and Binary Tree\n");
printf("Choose one Option:\n\n");
printf("1.Insert Student\n");
printf("2.Remove Student\n");
printf("3.Print 1 student\n");
printf("4.Print all student\n");
printf("5.Exit\n\n");
int option=0, inputID;
char inputname[50];
List* head = malloc(sizeof(List));
scanf("%d", &option);
switch(option)
{
case 1:
printf("Enter Student name: ");
scanf("%s", inputname);
printf("Enter Student ID: ");
scanf("%d", &inputID);
Linked_insert(inputname, inputID, start, head);
start = 1;
break;
case 2:
break;
case 3:
break;
case 4:
Print_all(head);
break;
case 5:
loop =1;
break;
default:
loop =1;
break;
}//end of switch
}//end of infinte loop
}//end of main
【问题讨论】:
-
也不编译
-
我不知道该放什么来代替 void。我也不确定如何更新头部,这就是我在这里问的原因
-
很多很多问题都是从地面开始的。来自错误的类型名称(不是 List,建议使用 ListItem)。破碎列表实现(
head角色难以理解)
标签: c linked-list