【发布时间】:2020-06-13 15:24:37
【问题描述】:
我得到一个头文件,它定义了如何创建链表的节点
#ifndef _LISTNODE
#include <cstddef>
#define _LISTNODE
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
#endif
我的任务是创建一个函数,该函数将对链表进行插入排序并按降序对项目进行排序(可以假设链表中没有循环。
函数定义为
ListNode *insertionSortList(ListNode *head)
所以我现在的逻辑是遍历链表,直到发现迭代器当前所在的节点小于它旁边的节点的值。在这种情况下,它获取包含较大数字的节点的值并将其存储在临时指针中。然后我的迭代器位于刚刚放入临时指针的节点之前的数字上,使得该节点现在指向破坏顺序的节点并指向之后的节点。
然后我让另一个迭代器遍历列表,直到它找到它可以使订单工作的位置,然后将存储的节点与 temp 指针一起放置,并使该节点内的 next 指针指向新迭代器发现小于它的节点。
如果这个解释有点混乱,我很抱歉,但是当我绘制图表时它似乎是有道理的,而且我没有看到我的代码可能会破坏这个逻辑,但是当我通过一些测试运行它时在这种情况下,它要么不排序,要么有时不排序并且不打印所有值。
#include <iostream>
#include "ListNode.h"
using namespace std;
ListNode *insertionSortList(ListNode *head)
{
ListNode *temp;
for (ListNode *iterator = head; iterator->next != NULL; iterator = iterator->next) //first iterator to find node that breaks the pattern
{
if (iterator->val >= iterator->next->val) // if it doesn't break the pattern
{
break;
}
else //if it does break the pattern
{
temp = iterator->next; //store pattern breaking node
iterator->next = iterator->next->next; //have linked list skip over this pattern breaking node
for (ListNode *replacementit = head; replacementit->next != NULL; replacementit = replacementit->next) // find place for patteern breaking node
{
if (replacementit->val < temp->val) //if found the right place
{
temp->next = replacementit; //put node into place
break;
}
}
}
}
return head;
}
int main() //test cases
{
ListNode A(5);
ListNode B(6);
ListNode C(10);
ListNode D(21);
ListNode E(25);
ListNode* head = &A;
A.next = &B;
B.next = &C;
C.next = &D;
D.next = &E;
insertionSortList(head);
for (ListNode *print = head; print->next != NULL; print = print->next) //print out sorted Linked List
{
cout << print->val << " ";
}
}
输出
5 10 %
【问题讨论】:
-
是的,我花了很多时间阅读和观看视频,试图了解插入排序的工作原理,我相信我的函数逻辑遵循我所看到的关于插入排序应该如何工作的内容,这就是为什么我很困惑我可能哪里出错了
-
您是否使用 调试器 逐步执行程序以找出它开始偏离您的期望的地方?
-
对不连续的数据结构进行排序听起来确实不太好。在这些情况下,让插入保持数据结构排序,而不是事后排序。
标签: c++ linked-list insertion-sort