2017-10-21 6 views
-1

3つのファイル "Source.cpp、Queue.h、Queue.cpp"にコードを書きました。リンクリスト付きキューのコードでバグが見つからない

プログラムを実行するたびに、エラーが表示され、その理由がわかりません。必要なすべてのライブラリが含まれています。

//Source.Cppその中のすべての機能を持つファイル.header "主な機能"

Queue<int>X; 
//trying to run the program . 
for (int i = 0; i < 5; i++) 
{ 
    X.Push(i + 1); 
    cout << X.Size() << endl; 
} 
X.front();/ 
X.Pop(); 
X.front(); 
X.Pop(); 


return 0; 

//Queue.h

//ノードクラス。

template<class Mine> 
class Node 
{ 
public: 
    Mine Value; 
    Node<Mine> *Prev; 
    Node(); 
    Node(Mine); 
}; 

template<class Mine> 
    //Queue Class 
class Queue 
{ 
    int Elements; 
    Node<Mine> *Front, *Back; 

public: 
    Queue(); 
    ~Queue(); 
    int Size();//returns Queue Size 
    void Push(Mine);//Push a new value to the back 
    void Pop();//removes a value from the front 
    void Clear();// delete all the elements 
    bool isEmpty();// checks if there are no elements in the queue 
    Mine front();//returns the value in the front 

}; 

//Queue.cpp

//実装私が書いた.theのコード。

template<class Mine> 
Node<Mine>::Node() 
{ 
Value = 0; 
Prev = 0; 
} 

template<class Mine> 
Node<Mine>::Node(Mine Value) 
{ 
this->Value = Value; 
Prev = 0; 
} 

template<class Mine> 
Queue<Mine>::Queue() 
{ 
Elements = 0; 
Front = Back = 0; 
} 

template<class Mine> 
Queue<Mine>::~Queue() 
{ 
Clear(); 
} 

template<class Mine> 
int Queue<Mine>::Size() 
{ 
return Elements; 
} 

template<class Mine> 
void Queue<Mine>::Push(Mine Value) 
{ 
Node<Mine> *NEW = new Node<Mine>(Value); 
if (Front==0) 
    { 
    Front = Back = NEW; 
    Back->Prev = 0; 
    } 
else 
    { 
    Back->Prev=NEW; 
    Back = NEW; 
    Back->Prev = 0; 
    } 
    Elements++; 
} 

template<class Mine> 
void Queue<Mine>::Pop() 
{ 
Node<T>*tmp; 
assert(!isEmpty()); 
tmp = Front->Prev; 
delete Front; 
Front = tmp; 
delete tmp; 

if (Elements==1)Front=Back; 
Elements--; 

} 
    template<class Mine> 
    void Queue<Mine>::Clear() 
    { 
    for (int i = 0; i < Elements; i++) 
    { 
     Pop(); 
    } 
    } 
    template<class Mine> 
    bool Queue<Mine>::isEmpty() 
    { 
    return Elements == 0; 
    } 
    template<class Mine> 
    Mine Queue<Mine>::front() 
    { 
    assert(!isEmpty()); 
    return Front->Value; 
    } 

プログラムを実行するたびに動作を停止します。

+0

C++のキューstlを使用しない理由、なぜあなたは車輪の人を再発明していますか? –

+1

@Ahmed Samy少なくとも関数void Queue :: Pop()が間違っています。たとえば、このFront = tmp; 削除tmp; は意味がありません。 –

+0

質問にエラーメッセージを追加してください。 –

答えて

1

メンバー関数Popが間違っています。まず第一に、それはキュー

delete Front; 
Front = tmp; 
delete tmp; 

で一度に二つのノードを削除し、それが結果キューがPopを呼び出した後に空である場合には0にBackを設定しません。このデータメンバはすでにのコンストラクタで0に設定されているため

関数は次のよう

template<class Mine> 
void Queue<Mine>::Pop() 
{ 
    assert(!isEmpty()); 

    Node<T> *tmp = Front->Prev; 
    delete Front; 

    Front = tmp; 

    if (--Elements == 0) Back = nullptr; 
} 

を見ることができます。また、この

Back->Prev = 0; 

のようなステートメントは、メンバ関数Pushに冗長ですノード。

それはクラスQueueの実装の詳細であるため、設計の観点から、クラスNodeは、クラスQueueの内部のプライベートな構造でなければなりません。

データメンバの名前をPrevからNextに変更すると、論理的に一貫性があります。

関連する問題