-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
};
おかげ
してください[編集]あなたの質問のような条件を書き換える必要があります。 –
ようこそスタックオーバーフロー。 [The Tour](http://stackoverflow.com/tour)を読み、[ヘルプセンター](http://stackoverflow.com/help/asking)の資料を参考にしてください。ここに聞いてください。 –
このような問題を解決する適切なツールは、デバッガです。スタックオーバーフローを尋ねる前に、コードを一行ずつ進める必要があります。詳しいヘルプは、[小さなプログラムをデバッグする方法(Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を参照してください。少なくとも、問題を再現する[最小、完全、および検証可能](http://stackoverflow.com/help/mcve)の例と、デバッガでの観察結果を含めるように質問を編集する必要があります。 –