簡體   English   中英

檢查鏈表是否在 C 中排序(升序)?

[英]Check if Linked List is sorted (ascending order) or not in C?

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;

}

我總是得到“升序”,請幫我找出問題所在。 這是完整的源代碼,鏈接列表代碼

如果您仔細查看您的代碼,您會在創建列表時對列表的元素進行排序:

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

如果您評論列表的排序,您將獲得預期的結果。

在任何情況下,無論列表是否已經排序,function 都不正確。

對於初學者,它可能具有未定義的行為,因為用戶可以調用 function 以獲得空列表。 在這種情況下,這個表達式

ptr->next != NULL

將調用未定義的行為。

function 不得 output 任何消息。 它是 function 的調用者將決定是否給 output 任何消息。 它應該做的是返回 integer 值 0 或 1,報告列表是未排序的還是排序的。

此外,要得出列表未排序的結論,無需遍歷它。 變量countcount2沒有意義。 它們是多余的。

function 可以通過以下方式定義。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM