c - 排序链表函数(C)

标签 c sorting data-structures linked-list

我是一名初学者,过去几周一直在自学数据结构。我正在尝试创建一个函数,以排序的方式将整数插入到链表中。

这是我的功能:

void sortedInsert(int n)
{
    node *temp = malloc(sizeof(node));
    temp->data= n;

    //if list is empty or n is less than minimum number in the list, insert at the beggining.
    if(head == NULL || n < head->data )
    {
        temp->next = head;
        head = temp;
    }
    else
    {
        node *cur, *prev, *temp;
        for (cur = head, prev = NULL
             cur != NULL && cur->data < n;  //if n is less than cur->value it breaks out of loop
             prev = cur, cur = cur->next);

         //now cur is pointing at last node or the node it broke out off

         if( n < cur->data)
         {
             temp->next = cur;
             prev->next = temp;
         }
         else
         {
             //if its larger than the maximun number in the list
             //insert at end 
             temp->next = NULL;
             cur->next = temp;
         }

         free(cur);
         free(prev);
    }
}

输出:

How many numbers?
4
Enter the number
10
List is:  10
Enter the number
4
List is:  4 10
Enter the number
5

Process returned -1073741819 (0xC0000005)   execution time : 7.161 s
Press any key to continue.

每当我插入的数字大于列表中的数字时,它就会崩溃。 如果我能得到任何帮助或指导,我将不胜感激。

最佳答案

错误行为在 else 语句内的 for 循环中。该循环在两种情况下终止。第一个是,如果找到一个数据大于或等于 n 的节点。第二种是当 cur 为 NULL 时。如果遍历所有链表才找到一个值大于等于n的节点,则循环会在cur变为NULL时终止。

因此您需要检查 cur 是否为 NULL,并且您不应该使用它,因为它肯定是一个非 NULL 的值。

为了实现您想要的行为,我相信您应该去掉 for 循环后面的 if-else 语句,而只使用下面的两行。

temp->next = cur;
prev->next = temp;

除此之外,在 for 循环之前,您再次声明 temp 变量会导致您在函数开头声明的 temp 对于该范围不可访问。第二个声明也应删除。

最后,虽然您没有指定函数的预期行为,但根据函数名称的语义含义,我相信您不需要调用 free(),您应该删除它们。

因此,在进行我提到的更改之后,您的代码应该如下所示。

void sortedInsert(int n)
{
    node *temp = malloc(sizeof(node));
    temp->data= n;

    //if list is empty or n is less than minimum number in the list, insert at the beggining.
    if(head == NULL || n < head->data )
    {
        temp->next = head;
        head = temp;
    }
    else
    {
        node *cur, *prev;
        for (cur = head, prev = NULL
             cur != NULL && cur->data < n;  //if n is less than cur->value it breaks out of loop
             prev = cur, cur = cur->next);

         //now cur is pointing at last node or the node it broke out off
         temp->next = cur;
         prev->next = temp;
    }
}

关于c - 排序链表函数(C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319852/

相关文章:

c - 在 C 中以流方式读取和处理内存中的 XML 数据

c - 如何在套接字服务器应用程序中重用端口?

c - C 初学者 : Getting frustrated on a simple program

java - 在 Java 8 流中按属性排序

data-structures - HashMap 和 HashTable 纯粹在数据结构上的区别

c - 如何创建在 .txt 文件中搜索单词并计算它在 C 中出现的次数的代码?

javascript - javascript中查找数组中重复元素的方法有哪些

ruby - 多线程归并排序

sorting - 如何使用自定义顺序对 kotlin 中的对象数组进行排序?

c - 如何解决file.exe在链表中插入一次后停止运行的问题