对于我的作业,我必须创建一个单链表并插入3个项目。我尝试使用面向对象的方法,而不是我的老师和几乎所有其他人使用的纯指针方法; head和tail都是我的列表类的节点和属性。我的代码唯一的问题是头节点的指针不会更新到下一个节点。任何人都可以帮我纠正这个吗?
#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();
};
答案 0 :(得分:1)
头部和尾部节点应保留为虚拟节点,而不是列表的一部分。头部和尾部节点的元素值不需要初始化或检查。非空列表的插入序列是
// ...
v->ptr = head.ptr;
head.ptr = v;
// ...
看看你是否可以修复剩下的代码。
如果创建追加函数,则非空列表的追加序列为
// ...
v->ptr = NULL;
tail.ptr->ptr = v;
// ..