簡體   English   中英

雙向鏈表的插入排序 C

[英]Insertion sort of a doubly linked list in C

我正在嘗試在雙向鏈表中實現插入排序算法,這是我的代碼:

void insertion_sort_list(listint_t **list)
{
        listint_t *head, *insert, *temp, *aux;

        head = *list;
        while (head)
        {
                insert = head->next;
                aux = head;
                while (aux && aux->n > insert->n)
                {
                        temp = aux->next->next;
                        aux->next = temp;
                        temp->prev = aux;
                        aux = aux->prev;
                }
                temp = aux->prev;
                insert->next = aux;
                insert->prev = temp;
                head = head->next;
        }
}

我已經嘗試了代碼,但它給了我一個無限循環。 當我嘗試在我的調試器中運行它時,我無法理解它(我的可執行文件是從多個文件編譯而來的)。 有人能幫我找出我的錯誤在哪里嗎,我以后怎么能找到這類錯誤(無限循環)? 如果可能的話,你能給我推薦一份文檔或任何東西,這將幫助我使用gdb調試從多個 C 文件編譯的可執行文件。 謝謝你。

我要回答我自己的問題。 所以這個問題讓我花了將近兩天的時間想弄清楚如何在雙向鏈表中實現插入排序算法。 我不喜歡抄別人的代碼,因為我抄了干嘛要學。

這是我解決問題的方法:

void insertion_sort_list(listint_t **list)
{
        listint_t *sorted, *curr, *next, *aux, *temp;

        sorted = NULL;
        curr = *list;

        while (curr != NULL)
        {
                next = curr->next;

                if (sorted == NULL || sorted->n > curr->n)
                {
                        curr->next = sorted;
                        sorted = curr;
                } else
                {
                        aux = sorted;

                        while (aux->next != NULL && aux->next->n <= curr->n)
                                aux = aux->next;

                        if (aux->next == NULL)
                        {
                                aux->next = curr;
                                curr->prev = aux;
                                curr->next = NULL;
                        } else
                        {
                                temp = aux->next;
                                aux->next = curr;
                                curr->prev = aux;
                                curr->next = temp;
                                temp->prev = curr;
                        }
                }

                curr = next;
        }

        *list = sorted;
}

如您所見,我沒有向后遍歷,而是制作了一個虛擬頭部,這樣我就可以對列表進行排序。 這種方法比我以前的方法干凈得多。 我明白算法很難,實現它們需要時間。 而我,之前只實現了冒泡排序,至少花了兩天時間想出了一個解決方案。 但它會讓你對這個概念有更多的了解。

暫無
暫無

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

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