gpt4 book ai didi

c - 如何在运行时创建单链表并对其进行排序?

转载 作者:行者123 更新时间:2023-11-30 16:32:35 24 4
gpt4 key购买 nike

我正在尝试通过读取文本文件创建一个链接列表,并按升序输出读取的单词及其计数。

除了尝试在运行时对节点进行排序之外,一切都很好。

首先,我尝试过冒泡排序,但我无法理解链表开头部分的逻辑。

其次,我尝试继续比较 x->next 的计数,直到找到一个比我想要推回的计数更大的计数。然后我交换它们。我使用了很多指针,但有时它可以工作,但在某些边缘情况下会失败。

我应该保存一些代码,让人们指出我的逻辑缺陷,但我有点沮丧,只是试图从头开始。

有人可以提供一些好的逻辑或明确的伪代码吗?非常感谢

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#define MAX 999
typedef struct Node
{
char *name;
int count;
struct Node *next;
}node;
void insert(node **,char *);
void freeNode(node **);
int main()
{
char str[MAX];
node *head = NULL;
while(getword(str,MAX))
{
insert(&head,str);
}
print(head);
free(head);
return 0;
}
void insert(node **head,char *str)
{
node *mid = *head;
node *left = NULL, *right = NULL;
while(mid)
{
if(strcmp(mid->name,str) == 0)
{
++(mid->count);
node *temp = left;

while(mid->count > right->count)
{
//printf("in %s %s %s\n",left->name,mid->name, right->name);
left->next = mid->next;
mid->next = right->next;
right->next = mid;

left = left->next;
if(mid->next != NULL) right = mid->next;
if(left == mid) break;
//printf("in %s %s %s\n\n",left->name,mid->name, right->name);
// sleep(3);
}

return;
}
left = mid;
mid = mid->next;
if(mid != NULL) right = mid->next;
}

node *newnode = (node *) malloc(sizeof(node));
newnode->name = (char *) malloc(MAX * sizeof(char));
strcpy(newnode->name,str);
newnode->count = 1;
newnode->next = *head;
*head = newnode;
}
void freeNodes(node **head)
{
node *temp;
while(*head)
{
temp = (*head)->next;
free(*head);
(*head) = NULL;
(*head) = temp;
}
}

最佳答案

我刚刚处理了一些边缘情况。我确保当第一个节点重复时将确保向下移动一个

node *mid = *head;
node *left = NULL, *right = NULL;
while(mid)
{
if(strcmp(mid->name,str) == 0)
{
++(mid->count);
if(mid->next == NULL) return;
node *temp = left;
if(left == NULL)
{
left = mid->next;
mid->next = left->next;
left->next = mid;
*head = left;
right = mid->next;

}
while(mid->count > right->count)
{
left->next = mid->next;
mid->next = right->next;
right->next = mid;

left = left->next;
if(mid->next != NULL) right = mid->next;
if(left == mid) break;
//printf("in %s %s %s\n\n",left->name,mid->name, right->name);
// sleep(3);
}

return;
}
left = mid;
mid = mid->next;
if(mid != NULL) right = mid->next;
}

关于c - 如何在运行时创建单链表并对其进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50084971/

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