對於我的任務,我必須創建一個單鏈表並插入3個項目。我嘗試使用面向對象的方法,而不是純粹的指針方法,我的老師和幾乎所有人都使用;頭部和尾部都是我的列表類的節點和屬性。我的代碼唯一的問題是頭節點的指針不會更新到下一個節點。任何人都可以幫我解決這個問題單鏈表C++:頭指針不連接到下一個節點
#include <iostream>
using namespace std;
class node
{
public:
int element;
node* ptr;
friend class list;
};
class list
{
public:
//Including head and tail attributes and making them public so that
they are easily accessible to anyone using the linked list construction
node head;
node tail;
list()
{
head.element = -1; //-1 is sentinel value
tail.element = -1;
head.ptr = NULL;
tail.ptr = NULL;
head = tail;
}
bool empty()
{
return((head.ptr == NULL) && (head.element == -1));
}
void insert(int a)
{
if(empty())
{
head.element = a;
tail.element = a;
}
else
{
//Making a new unnamed node, inserting the new value, and
updating the tail attribute
node* v = new node;
tail.ptr = v;
v -> element = a;
v -> ptr = NULL;
tail.element = v-> element;
tail.ptr = v -> ptr;
}
}
void print()
{
int i = 0;
node *pointer = head.ptr;
while(pointer != NULL)
{
cout << "The " << i+1 << "th element is: " << pointer ->
element;
pointer = pointer -> ptr;
i++;
}
}
};
int main()
{
int values[3] = {1, 2, 3};
list lst;
for(int i = 0; i < 3; i++)
{
lst.insert(values[i]);
}
cout << lst.head.element << endl;
cout << lst.tail.element;
lst.print();
};
「頭」和「尾」是指您構建它們的方式都完整列表。你只追尾,只能從頭上讀。 – PeterT
類和成員函數本身不會使您的程序面向對象;在C++中,OO通常具有* inheritance *和* virtual functions *。 –
另請注意,您的代碼包含無償的特殊情況。一個空列表沒有元素;引入一個帶有特殊「定點」值的需要更多的檢查,並且使得你的代碼更加複雜,更容易出錯,並且不那麼通用。你可能會得到一個降低的標記。 –