提问人:Noah Nininger 提问时间:2/23/2023 最后编辑:chqrlieNoah Nininger 更新时间:2/23/2023 访问量:37
打印排序列表时缺少节点 (C)
Missing Node while Printing a Sorted List (C)
问:
我有一个按字母顺序排序的链表;但是,在打印列表时,我似乎在输出中缺少一个节点,我相信正在发生的事情是其中一个节点在交换时被设置为 NULL。
int compare_by_lastname(node_t *a, node_t *b) // these two functions
{ return strcmp(a->lastName, b->lastName); } // compare two nodes
int compare_by_firstname(node_t *a, node_t *b)
{ return strcmp(a->firstName, b->firstName); }
void swapNode(node_t* a, node_t* b) // helper function for sortList()
{
node_t temp = *a;
*a = *b;
*b = temp;
}
void sortList(node_t **head, int (*comp)(node_t*, node_t*)) // sorting using function pointer
{
node_t *temp1 = NULL;
node_t *temp2 = NULL;
int swapped = 0;
if (*head == NULL)
{ return; }
do
{
swapped = 0;
temp1 = *head;
while (temp1->next != temp2)
{
if (comp(temp1, temp1->next) > 0)
{
swapNode(temp1, temp1->next);
swapped = 1;
}
temp1 = temp1->next;
}
temp2 = temp1;
} while (swapped);
}
这是打印我的列表的代码块
while (temp != NULL) // node_t* temp = head
{
// if provided day of the month is invalid, skip to the next node
if (checkInvalidDate(temp) == true)
{ temp = temp->next; }
fprintf(out, "Name:\t%s %s\n", temp->firstName, temp->lastName);
fprintf(out, "Date of Birth:\t%s %s, %s\n", temp->bd.month,
temp->bd.day,
temp->bd.year);
fprintf(out, "Major:\t%s\n", temp->major);
fprintf(out, "Year:\t%s\n\n", temp->classStanding);
temp = temp->next; // next element
}
此外,下面是代码从中读取以创建列表的文件。
Nininger,Noah,July,31,2002,CS/BS,Junior
Doe,Jane,December,12,2003,CS/BS,Sophomore
Doe,John,December,12,2003,CS/BS,Sophomore
Joe,Average,February,3,2002,CS/BS,Freshman
排序函数似乎确实根据需要对列表进行排序,但我认为其中一个节点是 NULL,因为该问题仅在实现sortList()
答: 暂无答案
评论
next