データ構造クラスのリンクリストを実装しようとしていますが、アルゴリズムの検索部分に問題があります。C++リンクリスト実装がクラッシュする
以下IテキストをアルゴリズムMIT導入における擬似コード次実装しようとしている問題のコードである:、
//
// Method searches and retrieves a specified node from the list
//
Node* List::getNode(unsigned position)
{
Node* current = m_listHead;
for(unsigned i = m_listSize-1; (current != 0) && (i != position); --i)
current = current->next;
return current;
}
この時点で頭プログラムでは4ノードでありますint 5の値を含んでいます。問題はfor-loopの本体にあるように見えます。ここで、ノードオブジェクトへのポインタは次のノードに割り当てられます。しかし、これはノードの頭を越えているので、本質的にメモリ内のいくつかのランダムな場所を指しています(これは理にかなっています)。
この場合、アルゴリズムは次のノードの代わりに前のノードに移動してはなりませんか?以下は擬似コードです:
LIST-SEARCH(L, k)
x <- head
while x != NIL and key != k
do x <- next[x]
return x
また、私のリンクリストの実装のヘッダーファイルは次のとおりです。私は物事をシンプルに保つために、まだテンプレートの形でそれを実装しようとしていない:に、addNodeメソッドの
#ifndef linkList_H
#define linkList_h
//
// Create an object to represent a Node in the linked list object
// (For now, the objects to be put in the list will be integers)
//
struct Node
{
// nodes of list will be integers
int number;
// pointer to the next node in the linked list
Node* next;
};
//
// Create an object to keep track of all parts in the list
//
class List
{
public:
// Contstructor intializes all member data
List() : m_listSize(0), m_listHead(0) {}
// methods to return size of list and list head
Node* getListHead() const { return m_listHead; }
unsigned getListSize() const { return m_listSize; }
// method for adding a new node to the linked list,
// retrieving and deleting a specified node in the list
void addNode(Node* newNode);
Node* getNode(unsigned position);
private:
// member data consists of an unsigned integer representing
// the list size and a pointer to a Node object representing head
Node* m_listHead;
unsigned m_listSize;
};
#endif
実装:
//
// Method adds a new node to the linked list
//
void List::addNode(Node* newNode)
{
Node* theNode = new Node;
theNode = newNode;
theNode->next;
m_listHead = theNode;
++m_listSize;
}
は、二重リンクリストですか?記憶のように見えるのは何ですか? – Dave
問題はaddNodeのメンバー関数にあると思います。リストが正しく構築されるように、そのコードを提供してください。 –
上記のコード。 – dtg