gpt4 book ai didi

c - 将节点插入此链表的最佳方法?

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:26 25 4
gpt4 key购买 nike

这是我的链表程序代码。我知道它不是那么好,但它确实有效。我想更改 ins() 函数,以便按大小将新元素插入到列表中。即,列表中的最后一个节点将包含最大的整数,最小的第一个。整数是从文本文件中读入的,正如您在 main() 中看到的那样,文本文件中的 INSERT 和 REMOVE 命令被解释为将(下一行的以下整数)插入列表的命令,或者从列表中删除一个元素。我怎样才能用我现有的代码做到这一点?我尝试修改我的 ins() 函数,但无法正确排序我的列表。

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

struct node {
int number;
struct node *next;
};

/* prototypes */

void ins(struct node *llist, int number);
void rem(struct node *llist);
void sho(struct node *llist);

int main(void)
{
int number;
char command[6];
struct node *llist;
struct node *root;

llist = (struct node *)malloc(sizeof(struct node));
llist->number = 0;
llist->next = NULL;

root = llist;

printf("addr: \n\n%p,%p\n\n", &llist, &root);

FILE *file;
file = fopen("a3data.txt", "r");

if (file == NULL)
{
printf("\n----------------------------------------\n");
printf("| Error. Did not read file. Exiting. |\n");
printf("----------------------------------------\n\n");
exit(1);
}
else
{
while ((fscanf(file, "%s", command)) != EOF)
{
if((strcmp(command, "INSERT"))==0)
{
fscanf(file, "%d", &number);
printf("\nINSERT ", number);
ins(llist, number);
sho(llist);
}
else if((strcmp(command, "REMOVE"))==0)
{
printf("\n REMOVE ");
rem(llist);
sho(llist);
}
}
}

printf("\n");
free(llist);
return(0);
}

void ins(struct node *llist, int number)
{
while(llist->next != NULL)
{
llist = llist->next;
}

llist->next = (struct node *)malloc(sizeof(struct node));
llist->next->number = number;
llist->next->next = NULL;
}

void rem(struct node *llist)
{
while(llist->next->next != NULL)
{
llist = llist->next;
}

llist->next = NULL;
}

void sho(struct node *llist)
{
while(llist->next != NULL)
{
printf("%d ", llist->number);
llist = llist->next;
}

printf("%d", llist->number);
}

最佳答案

在你的情况下修改功能

void ins(struct node *llist, int number) 
{
struct node *llist1;
while(llist->next != NULL)
{
if (llist->next->number > number)
break;
llist = llist->next;
}

llist1 = (struct node *)malloc(sizeof(struct node));
llist1->number = number;
llist1->next = llist->next;
llist->next = llist1;
}

关于c - 将节点插入此链表的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17739645/

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