gpt4 book ai didi

c - 插入节点链表 C

转载 作者:太空宇宙 更新时间:2023-11-04 04:14:30 24 4
gpt4 key购买 nike

我正在尝试创建一个链表来存储学生的姓名和年龄。我在插入时遇到问题。

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>

typedef struct node{

char Name[50];
int studentAge;
struct node* next;

}MyNode;

这就是我定义结构的方式,它包含所需数据和指向下一个节点的指针“next”。

下面是我的插入函数所以在第一个 if 条件下我说如果没有头即 head = NULL 然后使用 malloc 为头创建内存空间..在此之后我将所有数据复制到头节点并确保头的下一个指向空。

在第二种情况下,我说的是是否有头,即头! = 空然后使用当前指针遍历列表到末尾,然后将所有数据复制进去。

void InsertStudent(char givenName[50], int age, MyNode* head){

if(head == NULL){
head = (MyNode*) malloc(sizeof(MyNode));
strcpy(head->Name,givenName);
head->studentAge = age;
head->next = NULL;
}


if(head != NULL){
MyNode* current = head;
while(current->next != NULL){
current = current->next;
}
current->next = (MyNode*) malloc(sizeof(MyNode));
strcpy(current->next->Name,givenName);
current->next->studentAge = age;
current->next->next = NULL;
}

}

现在我不确定我的打印或插入是否有问题,因为当我尝试代码时它没有打印我的节点

void PrintList(MyNode* head){
MyNode* current = head;

while(current != NULL){
printf("Name is %s Age is %d\n",current->Name,current->studentAge);
current = current->next;
}

}

这是我的主要功能.. MyNode* head = NULL; 有问题吗?允许的代码行吗?

  int main()
{


MyNode* head = NULL;

int r = 0;
while(r!=1)
{
printf("Data Structures - Linked List\n");
printf("Choose one Option:\n\n");
printf("1.Insert Student\n");
printf("2.Remove Student\n");
printf("3.Print all student\n");
printf("4.Exit\n");

int option=0;
char givenName[50];
int givenAge;
scanf("%d",&option);

switch(option){

case 1:
printf("Enter name of student: ");
scanf("%s",givenName);
printf("\nEnter Age of student: ");
scanf("%d",&givenAge);
InsertStudent(givenName,givenAge,head);
break;

case 2:
printf("Enter name of student: ");
scanf("%s",givenName);
printf("\nEnter Age of student: ");
scanf("%d",&givenAge);
RemoveStudent(givenName,givenAge);
break;

case 3:
PrintList(head);
break;
case 4:
r=1;
break;
default:
r=1;
printf("\nNot an option\n");
break;

}

}
}

最佳答案

您没有将头指针的初始值设置为第一个节点,并且由于从未完成,列表仍然为空并且您像筛子泄漏雨水一样泄漏内存。

正如您所说,您希望使用指针到指针的语法,结果应如下所示。 (没有错误检查,您可能应该考虑添加):

void InsertStudent(char givenName[50], int age, MyNode** head)
{
while (*head)
head = &(*head)->next;

*head = malloc(sizeof **head);
strcpy((*head)->Name, givenName);
(*head)->studentAge = age;
(*head)->next = NULL;
}

使用头指针的地址从您的主程序调用(不要将其与您最初正确设置为 NULL 的头指针的地址混淆;将后者视为指针持有的值,前者作为头指针本身在内存中的住所)。

InsertStudent(givenName,givenAge, &head); // NOTE THIS

我离开了删除和列表清理的任务。

关于c - 插入节点链表 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53452734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com