本文介绍了在单链表上使用插入排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个分配给我一个随机数字列表的作业,我需要使用插入排序对它们进行排序.我必须使用一个单链表.我环顾了其他职位,但似乎无济于事.我知道什么是插入排序,但我只是不知道如何用代码编写.
So I have an assignment where I'm giving a random list of number and I need to sort them using insertion sort. I must use a singly linked list. I looked around at other posts but none seem to help. I get what insertion sort is but I just don't know how to write it in code.
Node* insertion_sort(Node* head) { Node* temp = head_ptr; while((head->n < temp->n) && (temp != NULL)) temp = temp->next; head->next = temp->next; temp->next = head; head->prev = temp; }我不知道这是对的还是现在该怎么做
I dont know if this is right or what to do now
推荐答案struct node { int data; struct node *next; }; void insertion(struct node **head) { if((*head)== NULL || (*head)->next == NULL) { return; } struct node *t1 = (*head)->next; while(t1 != NULL) { int sec_data = t1->data; int found = 0; struct node *t2 = *head; while(t2 != t1) { if(t2->data > t1->data && found == 0) { sec_data = t2->data; t2->data = t1->data; found = 1; t2 = t2->next; } else { if(found == 1) { int temp = sec_data; sec_data = t2->data; t2->data = temp; } t2 = t2->next; } } t2->data = sec_data; t1 = t1->next; } }
更多推荐
在单链表上使用插入排序
发布评论