C++ 链表向前推无法正常工作
这是给我带来麻烦的部分。在我的图表中,我将p指向头部,然后将我的新头部设置为p,但它在现实生活中不起作用。有什么建议吗C++ 链表向前推无法正常工作,c++,linked-list,C++,Linked List,这是给我带来麻烦的部分。在我的图表中,我将p指向头部,然后将我的新头部设置为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 po
{
// 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\u next()
是否错了。不幸的是,我不得不用它来完成这项任务。应该是这样的
p->next=头部
水头=p
Ie将新创建节点的next设置为head,并将head更改为新创建的节点您需要直接分配到p->next(如LIJIN C的回答中所示),或者使用set_next(节点*)功能。get_next()只返回p->next的值(即节点对象的地址),它不允许您修改它,这正是您要做的 set_next函数如下所示:
// Returned pointer is just for convenience, this could easily be void
Node* Node::set_next(Node* newNext)
{
return p->next = newNext;
}
然后,您的else块变为:
else
{
// p->next points to head
p.set_next(head);
head = p;
// head points to first node in the list
}
编辑:还有一件事。当前编写代码的方式(即,作为只能在一个方向上遍历的单链表)不需要尾部指针。即使您计划
pop_back()
,也必须遍历整个列表才能找到新的尾部head
是您所需要的全部。只要您将head设置为p->next,您就可以用p覆盖head。否则,您已经编写了这样的注释//head->next points to new node,但是正在将p->next指定给head,而不是head->next=p请!是的,如果有人怀疑的话,我是纳粹密码@MonisMajeed他正试图把头推到前面,所以他实际上想把头的原始地址分配给p->next。它成功了,但我有点困惑。为什么把头伸进()使它起作用?谢谢btw@user3743209head
是节点*——节点对象在内存中的位置——就像p
和p->next
一样,对吗?将head
传递给函数允许p
将head
的值分配给其next
成员。