我想實現鏈表結構的遞歸排序算法。 C語言。C:鏈表的遞歸排序
我的算法是這樣的: 1)找到列表 2最大值)從列表中刪除,並在頭節點 3)啓動算法再次從下一個節點 4插入)運行,直到到達列表的末尾
我有一些東西,但它不記得我的清單。我意識到我在某處犯了一個錯誤(可能是遞歸調用),但我無法理解如何解決它。
typedef struct Node{
int data;
struct Node* next;
} Node;
void insert(Node** head, int val)
{
//insert at top
Node* to_insert = (Node*)malloc(sizeof(Node));
to_insert->data = val;
to_insert->next = (*head);
(*head) = to_insert;
}
Node* sort_ll(Node* head)
{
//base case, iterated trough entire list
if(head == NULL)
return NULL;
int max = 0;
Node* tmp = head;
Node* to_move = tmp;
//find maximum value
while(tmp != NULL) {
if(tmp->data > max) {
max = tmp->data;
to_move = tmp;
}
tmp = tmp->next;
}
//if its currently top, leave it there
if(to_move == head) {
return sort_ll(head->next);
}
//find node with max value
tmp = head;
while(tmp->next != to_move) {
tmp = tmp->next;
}
//cut it out from the list
tmp->next = tmp->next->next;
free(to_move);
//insert value at the head of the list
insert(&head, max);
return sort_ll(head->next);
}
int main()
{
Node* list = NULL;
insert(&list, 3);
insert(&list, 6);
insert(&list, 7);
insert(&list, 2);
insert(&list, 1);
insert(&list, 5);
insert(&list, 4);
list = sort_ll(list);
Node* tmp = list;
while(tmp != NULL) {
printf("%d\n", tmp->data);
tmp = tmp->next;
}
return 0;
}
的'sort_ll'函數修改'head'(間接),但你不要效仿 「按引用傳遞」。我假設你這樣做是因爲該函數返回一個'Node *',但問題是'sort_ll'將會總是*返回'NULL'。使用調試器,並逐行執行代碼。 –
@Someprogrammerdude我也在試驗這個簽名'Node * sort_ll(Node ** head)',但沒有得到更好的結果,只有不同類型的錯誤行爲。你能再解釋一下嗎?或者提供一個例子? – Rorschach
'sort_ll'中有三個return語句。一個是'return NULL;'和另外兩個都是'return sort_ll(...);'它怎麼能返回一個非NULL? –