2017-06-17 105 views
-5

我需要使用插入排序對鏈接列表進行排序。 元素看起來像這樣 [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]

我不知道爲什麼...我覺得它應該可以工作......但也許其他人會發現問題。

主營:在.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文件中

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());` 

排序功能

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 
}; 

感謝您的幫助

+0

請[編輯]你的問題提供了[MCVE。 –

+0

歡迎使用堆棧溢出。請花些時間閱讀[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –

+0

解決這些問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,你應該[編輯]你的問題,以包含一個[Minimal,Complete,and Verifiable](http://stackoverflow.com/help/mcve)例子來重現你的問題,以及你在調試器中所做的觀察。 –

回答

0

,而不是比較值的指向指針在報表這樣

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

你比較指針本身。

你應該重寫條件類似

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