我想将节点添加到另一个结构中的stuct的链表中。
我的代码:
struct Courses{
char *courseName;
int creditValue;
Courses *next;
};Courses;
struct Student{
char *name;
int age;
Courses *list; //First course (node)
}Student;
现在我不确定如何通过学生结构为需要添加到列表的各种课程(节点)添加课程节点。
有人能告诉我这是怎么做到的吗?
答案 0 :(得分:1)
这是一个在头部添加一个节点的功能:
struct Courses{
char *courseName;
int creditValue;
struct Courses *next;
};
struct Student{
char *name;
int age;
struct Courses *list;
};
void addNodeAtHead( struct Student *student, struct Courses *newNode )
{
newNode->next = student->list; // successor of newNode is head of list
student->list = newNode; // new head of list is newNode
}
这是一个在尾部添加一个节点到列表中的函数:
void addNodeAtTail( struct Student *student, struct Courses *newNode )
{
newNode->next = NULL; // sucessor of newNode is NULL, because newNode becomes tail of list
if ( student->list == NULL )
student->list = newNode; // if list is empty, newNode will be head of list
else
{
struct Courses *temp = student->list;
while( temp->next != NULL ) // search last element in list
temp = temp->next;
temp->next = newNode; // successor of last node is newNode
}
}
请注意,如果您创建新列表,则必须使用list
初始化struct Student
的结构元素NULL
。
void addCourse( struct Student *s, const char* courseName, int creditValue )
{
struct Courses *course = malloc( sizeof( Courses ) );
course->courseName = malloc( strlen(courseName)+1 );
strcpy( course->courseName, courseName );
course->creditValue = creditValue;
addNodeAtTail( student, course );
}
struct Student *student = malloc( sizeof( Student) );
student->list = NULL;
....
addCourse( student, "course", 666 );
如何打印清单:
void printList( struct Student *student )
{
struct Courses *temp = student->list;
while( temp != NULL )
{
printf( "courseName: %s, creditValue %d\n", courseName, creditValue );
temp = temp->next;
}
}
答案 1 :(得分:0)
您的代码和之前的答案中有一些错误。我想你想要定义一个名为Courses的结构。你只需要做像
这样的事情struct Courses{
char *courseName;
int creditValue;
Courses *next;
};
如果您不想为每个变量实例键入struct Course。只需添加
typedef struct Courses Courses;
同样适用于学生结构。
struct Student{
char *name;
int age;
Courses *list; //First course (node)
};
首先,您应该使用用户定义的函数初始化struct变量,该函数给出struct student变量名,age并将指针设置为NULL。
例如
void init(struct Student* s, char * name, int age ){
s->age = age;
s->name = malloc(strlen(name) + 1);
strcpy(s->name,name);
s->list = NULL;
}
如果你想定义一个add_course函数 这是示例
void add_course(struct Student*s, char* course_name,int credit){
struct Courses* c = malloc(sizeof (struct Courses) );
c->courseName = course_name;
c->creditValue = credit;
c->next = NULL;
if (s->list == NULL)
s->list = c;
else{
while (s->list->next != NULL)
s->list->next = s->list->next->next;
s->list->next = c;
}
}
然后编写一个函数来清理malloc()
分配的资源我认为您是C的新手。如果您想运行我的代码,请添加必要的库,例如
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
更多问题请问...