使用链接列表和指针进行插入排序

时间:2017-06-17 12:09:03

标签: c++ sorting linked-list singly-linked-list insertion-sort

我需要使用插入排序对链表进行排序。 元素看起来像这样 [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
};

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

而不是像这样的语句中那样比较指针指向的值

if (n->me < curr->me)

你正在比较指针本身。

您应该重写像

这样的条件
if ( *n->me < *curr->me )
相关问题