【问题标题】:Check if Linked List is sorted (ascending order) or not in C?检查链表是否在 C 中排序(升序)?
【发布时间】:2020-07-26 13:29:29
【问题描述】:
struct node* acc_check(struct node *head) {

int count = 0, count2 = 0;
for (struct node *ptr = head; ptr->next != NULL; ptr = ptr->next) {
    count++;
    if (ptr->data <= ptr->next->data) {
        count2++;
    }
}
if (count == count2)
    printf("Ascending Order");
else
    printf("Not in Ascending Order");
return head;

}

我总是得到“升序”,请帮助我找出问题所在。 这是完整的源代码,LINKED LIST CODE

【问题讨论】:

  • 当您发现您的程序无法按预期运行时,您接下来会做什么?您是否尝试过自己调试它?如果有,你发现了什么?请在问题本身中提供代码,而不是作为外部链接。
  • 你有一个绝对没有排序的样本列表吗?当您将该列表作为输入单步执行代码时,countcount2 是否都会递增?如果是,在什么条件下。

标签: c algorithm sorting data-structures linked-list


【解决方案1】:

与列表是否已经排序无关,在任何情况下函数都不正确。

对于初学者,它可能具有未定义的行为,因为用户可以为空列表调用该函数。在这种情况下这个表达式

ptr->next != NULL

将调用未定义的行为。

该函数不应输出任何消息。函数的调用者将决定是否输出任何消息。它应该做的是返回整数值 0 或 1,报告列表是未排序的还是已排序的。

此外,要得出列表未排序的结论,无需遍历它到其末尾。变量countcount2 没有意义。它们是多余的。

函数可以通过以下方式定义。

int acc_check( const struct node *head ) 
{
    if ( head != NULL )
    {
        const struct node *prev = head;
        while ( ( head = head->next ) != NULL && !( head->data < prev->data ) )
        {
            prev = head;
        }
    }

    return head == NULL;
}

【讨论】:

    【解决方案2】:

    如果您仔细查看您的代码,您会在创建列表时对列表的元素进行排序:

        case 1: {
            head = create_11(head);
            head = sort_list(head);
        }
    

    如果您评论列表的排序,您将获得预期的结果。

    【讨论】:

    • 哦,谢谢我错过了这个。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 2021-03-27
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多