0
我想創建一個函數,將insert a node to the back of the list using linked list
。我是新來的使用鏈表,我已經嘗試了許多不同的方式在列表的末尾做插入,但似乎沒有任何工作。 main
傳遞值one at a time
以插入2 4 5 8 9
,輸出爲2 0 0 0 0
。我不是什麼導致這個問題。C++鏈接列表返回
.H
class Node
{
public:
Node() : data(0), ptrToNext(NULL) {}
Node(int theData, Node *newPtrToNext) : data(theData), ptrToNext(newPtrToNext){}
Node* getPtrToNext() const { return ptrToNext; }
int getData() const { return data; }
void setData(int theData) { data = theData; }
void setPtrToNext(Node *newPtrToNext) { ptrToNext = newPtrToNext; }
~Node(){}
private:
int data;
Node *ptrToNext; //pointer that points to next node
};
class AnyList
{
public:
AnyList();
//default constructor
void print() const;
//Prints all values in the list.
void destroyList();
//Destroys all nodes in the list.
~AnyList();
//destructor
int getNumOfItems();
void insertBack(int b);
void deleteFirstNode();
private:
Node *ptrToFirst; //pointer to point to the first node in the list
int count; //keeps track of number of nodes in the list
};
的.cpp
void AnyList::insertBack(int b)
{
Node *temp = new Node;
if (ptrToFirst == NULL)
{
temp->setData(b);
ptrToFirst = temp;
}
else
{
Node *first = ptrToFirst;
while (first->getPtrToNext() != NULL)
{
first = first->getPtrToNext();
}
first->setPtrToNext(temp);
}
}
我注意到你從來沒有在您發佈的代碼初始化ptrToFirst爲NULL。這將大大影響if(ptrToFirst == NULL)的邏輯,同時你也在它的初始化計數 – Diniden 2015-02-17 22:57:15
這裏是我的構造函數AnyList :: AnyList() \t ptrToFirst = NULL; \t count = 0; 「我忘了把它插入帖子中。 – Nignig 2015-02-17 23:04:59