排序链表功能(C)

时间:2016-12-25 08:56:04

标签: 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.

每当我插入一个大于列表中的数字时,它就会崩溃。 我会感激任何帮助或指导。

1 个答案:

答案 0 :(得分:1)

错误的行为是在else语句中的for循环中。该循环终止于两个条件。第一个是,如果找到数据大于或等于n的节点。第二个是cur为NULL时。如果在查找值大于或等于n的节点之前遍历所有列表,则当cur变为NULL时,循环将终止。

因此你需要检查cur是否为NULL,你不应该使用它,就好像它肯定是一个非NULL的值。

为了达到你想要的行为,我相信你应该摆脱for循环之后的if-else语句,而只是使用下面的两行。

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

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

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

因此,在进行了我提到的更改之后,这就是代码的外观。

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;
    }
}