【发布时间】:2018-10-12 00:47:59
【问题描述】:
所以我尝试将学生的信息(包括名字、姓氏、分数和邮政编码)输入到单个节点中。然后我就可以将另一个学生的信息插入下一个节点,依此类推,并能够访问它们。
我遇到问题的部分是将姓氏、分数和邮政编码添加到节点中。如果有人可以提供帮助,我将不胜感激。这可能很简单,但我就是不知道怎么做。
您可以在插入函数中看到问题。我可以插入名字,但不能插入姓氏。我的基础可能有问题,但如果是,请告诉我。
谢谢。
#include <stdio.h>
#include <stdlib.h>
/* inserting nodes at the END of a linked list */
void Insert(char *f, char *l, float s, char *z);
void Print();
struct node
{
struct Student *now;
struct node *next;
};
struct node *head; /* it will be created in the GLOBAL region of the memory */
struct node *tail = NULL;
struct Student {
char firstname[20];
char lastname[20];
float score;
char zip[20];
};
int main()
{
//int i,n,x;
//int x;
head = NULL;
char first[20];
char last[20];
float score;
char zip[20];
printf("\nPlease input records of students: ");
printf("\nFirst name: ");
scanf("%s", first);
printf("\nLast name: ");
scanf("%s", last);
printf("\nScore: ");
scanf("%f", &score);
printf("\nZip code: ");
scanf("%s", zip);
printf("\n------ This is the Print records function so far: \n\n");
Insert(first, last, score, zip);
Print();
return 0;
}
void Insert(char *f, char *l, float s, char *z)
{
struct node *temp = (struct node*) malloc(sizeof(struct node));
temp->now=f;
// Problem: how do I insert the other variables (last, score, zip) into a student structure and into node?
//temp->now.lastname =l; //Doesn't work
temp->next=NULL;
if (head == NULL)
{
head=temp;
tail=temp;
return;
}
tail->next=temp;
tail=temp;
}
void Delete(int n)
{
struct node* temp1 = head;
int i;
if (n==1)
{
head = temp1->next; /*head now points to the second node */
free(temp1);
return;
}
for(i=0; i<n-2; i++)
temp1=temp1->next; /* temp1 points to (n-1)th node */
struct node* temp2 = temp1->next; /* nth node */
temp1->next = temp2->next; /*(n+1)th node */
free(temp2); /* delete temp2 */
}
void Print()
{
struct node* temp = (struct node*) malloc(sizeof(struct node));
temp = head;
while (temp!=NULL)
{
printf("%s ",temp->now);
temp = temp->next;
}
printf("\n");
}
【问题讨论】:
-
now是指向struct Student的指针,f是指向字符的指针。其中一件事与另一件事不同......