【发布时间】:2017-11-20 03:06:55
【问题描述】:
我需要使用插入排序对链表进行排序。 元素看起来像这样 [0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 ]
排序的结果应该是这样的 [0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 ]
问题是我的结果看起来像这样 [ 3 2 1 0 3 2 1 0 3 2 1 0 3 2 1 0 3 2 1 0 ]
我不知道为什么......我觉得它应该可以工作......但也许其他眼睛会发现问题。
主要:
int main (int argc, char **argv) {
IntElement *ints[N_ELEMENTS];
for (int i = 0; i < N_ELEMENTS; i++) {
ints[i] = new IntElement (i%4);
}
SortedList slist;
for (int i = 0; i < N_ELEMENTS; i++) {
slist.addElement (ints[i]);
}
slist.print();
printf ("last = %s\n", slist.get (slist.size ()-1)->toString ());`
.cpp 文件中的排序功能
void SortedList::addElement(IElement * element)
{
entryPtr n = new entry;
n->next = NULL;
n->me = element;
curr = head;
if (curr == NULL) {
//Executes when linked list is empty
head = n;
return;
}
if (n->me < curr->me)
{
//Executes if given data is less than data in first node of linked list
n->next = head;
head = n;
return;
}
else
{
while (curr != NULL)
{
if (n->me>curr->me)
{
//Traverse to location we want to insert the node + 1 node
prev = curr;
curr = curr->next;
continue;
}
else
{
//Insert the node
prev->next = n;
n->next = curr;
return;
}
}
//Insert node at last
prev->next = n;
}
}
.h 文件
class SortedList {
protected:
typedef struct entry { // stores an element and a pointer to the next element in the list
IElement *me;
entry *next;
}*entryPtr;
entryPtr head;
entryPtr curr;
entryPtr prev;
entryPtr temp;
public:
SortedList();
~SortedList() {};
void addElement(IElement *element); // adds element to the list and returns position, -1 if not added
IElement *get(int position); // returns element at given position
int size(); // returns the number of elements in the list
void print(FILE *file = stdout); // prints all elements
};
感谢您的帮助
【问题讨论】:
-
请edit您的问题提供minimal reproducible example。
-
欢迎来到 Stack Overflow。请花时间阅读The Tour 并参考Help Center 中的材料,您可以在这里询问什么以及如何询问。
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行逐行检查您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该在edit 您的问题中包含一个重现您的问题的Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
标签: c++ sorting linked-list singly-linked-list insertion-sort