这是给我带来麻烦的部分。在我的图表中,我指向头部,然后将我的新头部设置为p,但它在现实生活中没有成功。有什么建议吗?
{
// p points to a new node
Node *p = new Node( s,0);
if( head == 0 ) // head not pointing to a node yet?
{
head = tail = p; // head & tail point to new node in the list
}
else
{ // head->next points to new node
head = p-> get_next();
head = p;
// head points to first node in the list
}
这是get_next()
函数。
Node *Node::get_next( ) const // get a Node * (value of next)
{
return next; //returns current objects pointer to next
}
我试着看一下我在网上看过的一些以前的案例,我开始怀疑我的get_next()
是不是错了。不幸的是,我必须将它用于此任务。
答案 0 :(得分:2)
应该是
p-> next = head;
头= P;
即将新创建的节点作为头部并将其改为新创建的节点
答案 1 :(得分:0)
你需要直接分配给p-> gt;(如LIJIN C的答案)或使用set_next(Node *)函数。 get_next()只返回p-> next的值(即Node对象的地址),它不允许你修改它,这就是你想要做的。 / p>
set_next函数看起来像这样:
// Returned pointer is just for convenience, this could easily be void
Node* Node::set_next(Node* newNext)
{
return p->next = newNext;
}
然后你的其他阻止变为:
else
{
// p->next points to head
p.set_next(head);
head = p;
// head points to first node in the list
}
编辑:还有一件事。当前编写代码的方式(即作为只能在一个方向上遍历的单链表),您不需要尾指针。即使您计划pop_back()
,您仍然需要遍历整个列表才能找到新的tail
。你只需要head
。