gpt4 book ai didi

c - 这段代码有什么有趣的错误吗?

转载 作者:行者123 更新时间:2023-11-30 21:20:47 27 4
gpt4 key购买 nike

抱歉这么长的代码,但我的错误对我来说非常有趣。我想根据许多学生的卷数创建一个排序的链接列表 ---

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef struct stuDetails
{
char name[15];
int age;
int roll;
struct stuDetails *next;
}det;

det *head;

void sortInsert(det *q, det *p);
void printSortedStructure(head);
void insSorted(det *p);

int j = 1, i;
int main(void)
{



head = (det *) malloc(sizeof(det));
head ->next = NULL;

insSorted(head);

puts("\n\nSorted Structure - \n");

printSortedStructure(head);


}


void insSorted(det *p)
{
printf("Type the name of student . Type nil to end.\n");
gets(p ->name);
if(j > 1)
{
gets(p ->name);
}
j++;
if(strcmp(p ->name, "nil") != 0)
{
printf("Type the age of student \n");
scanf("%d", &(p ->age));
printf("Type the roll no of student\n");
scanf("%d", &(p ->roll));
p ->next = NULL;
sortInsert(head, p);
p ->next = (det *) malloc(sizeof(det));
insSorted(p ->next);
}
else{
return;
}
}

void sortInsert(det *q, det *p)
{
if((p ->roll > q ->roll && p ->roll < q ->next ->roll) || q ->next == NULL || p ->roll == q ->roll || p ->roll == q ->next ->roll)
{
q ->next = p ->next;
p ->next = q;
return;
}
sortInsert(q ->next, p);
}

void printSortedStructure(det *head)
{
while(head ->next != NULL)
{
printf("Name : ", head ->name);
puts(head ->name);
printf("Age :%d\n", head ->age);
printf("Roll No :%d\n\n", head ->roll);
printSortedStructure(head ->next);
}

}

问题是当我运行程序时,它最多需要3个节点,然后停止工作。如果我只输入一个节点,然后输入“nil”作为下一个节点名称,它会打印结果中的第一个节点,并且程序再次停止工作。到底是什么问题?

最佳答案

如果你想在排序的线性喜欢列表中插入一个节点,你必须搜索前任节点并插入新节点作为找到的前任节点的后继节点

void sortInsert(det *head, det *p)
{
// search predecessor
det *pred = head;
while ( pred->next != NULL && p->roll < pred->next->roll )
pred = pred->next;

// insert new node next to pred
det *predNext = pred->next;
pred->next = p; // successor of predecessor is new node
p->next = predNext; // successor of new node ist old successor of predecessor node
}

在读取任何数据之前分配新节点:

void insSorted(det *head)
{
det *newNode = malloc( sizeof(det) );
newNode->next = NULL;
printf("Type the name of student . Type nil to end.\n");
gets( newNode->name );
if ( strcmp( newNode->name, "nil" ) != 0 )
{
printf( "Type the age of student \n" );
scanf( "%d", &( newNode->age ) );
printf( "Type the roll no of student\n" );
scanf( "%d", &( newNode->roll ) );
sortInsert( head, newNode );
}
else
free( newNode );
return;
}

您可以在简单的循环中打印节点。

void printSortedStructure(det *head)
{
det *act = head->next;
while( act != NULL )
{
printf("Name : %s\n", act->name );
printf("Age : %d\n", act ->age);
printf("Roll No : %d\n\n", act ->roll);
act = act->next;
}

}

关于c - 这段代码有什么有趣的错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34593028/

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