我正在尝试将节点插入到链接列表中,以便每个节点的数据中包含的字符串按字母顺序排序。如果输入重复的单词,则节点的“count”整数会增加。我得到了一个创建节点的 makeLnode() 函数、一个比较两个字符串的 isGreater() 函数以及一个返回每个节点的字符串的 getLnodeValue() 函数。
lnode insertWord(char * word, lnode head) {
/* Your code to insert a word in the linked list goes here */
lnode temp = makeLnode(word);
if(head == NULL) // if head is null, make head=temp
{
head = temp;
}
else if(isGreater(getLnodeValue(temp),getLnodeValue(head)) == -1) // if temp < head, place temp before head
{
temp->next = head;
head = temp;
}
else
{
lnode curr;
for(curr = head; curr; curr = curr->next) // loop through linked list
{
if(isGreater(getLnodeValue(temp),getLnodeValue(curr)) == 0) // if curr = temp, increment curr
{
curr->count++;
break;
}
else if(isGreater(getLnodeValue(temp),getLnodeValue(curr)) == -1) // if temp < curr, place temp before curr
{
temp->next = curr->next;
curr->next = temp;
break;
}
else if(curr->next == NULL) // if we reach the end of the list and temp > all other nodes, place temp at end of list
{
curr->next = temp;
break;
}
}
}
return head;
}
只有某些单词会递增,并且某些单词会有倍数。我的输出如下:
1. - 2 - a
2. - 2 - is
3. - 1 - broadcasting
4. - 1 - emergency
5. - 1 - be
6. - 1 - for
7. - 2 - this
8. - 1 - system
9. - 1 - system
10. - 1 - the
11. - 1 - testing
12. - 1 - seconds
13. - 1 - sixty
14. - 1 - next
15. - 1 - the
16. - 1 - test
17. - 1 - only
18. - 1 - test
19. - 1 - well
最佳答案
你说// if temp < curr, place temp before curr
但实际上是把它放在:
temp->next = curr->next;
curr->next = temp;
如您所见,因此您的输出没有排序。
isGreater
可能存在问题同样,也存在内存泄漏,但这应该是首先要修复的问题。
我不想在这里重构整个代码,因为这不是问题,如果还有问题,请随时询问。
关于c - 按字母顺序插入的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33245276/