双循环链表。新节点未插入。 C++
所以这个新节点应该插入到最后一个节点之后。我不明白为什么这种情况没有发生。注意:在调用此函数之前,列表有多个元素(大约 5 个),因此现在它只适用于这种情况。最后一个节点应指向顶部节点,并且 top->prev 指针应指向最后一个节点。我哪里出错了?顺便说一句,我假设它是错误的,因为调用打印函数时最后一个节点永远不会打印
void CircularDLL::insertAfterLast (int id, string name, string email, int age)
{
Node* N=new Node;
N->stId=id;
N->stName=name;
N->stEmail=email;
N->stAge=age;
Node* Q=top;
while(Q->next!=top)//get to the last node
{
Q=Q->next;
}
cout<<"Q next is top now"<<endl;
Q->next=N;
N->prev=Q;
N->next=top;
top->prev=N;
}
So this new node is supposed to be inserted after the last node. I can't figure out why that is not happening. Note: The list has multiple elements before this function is called (approx 5) so as of now it only has to work for that case. The last node should point to the top node and the top->prev pointer should point to the last node. Where have I gone wrong? I'm assuming that its wrong by the way because the last node never prints when the print function is called
void CircularDLL::insertAfterLast (int id, string name, string email, int age)
{
Node* N=new Node;
N->stId=id;
N->stName=name;
N->stEmail=email;
N->stAge=age;
Node* Q=top;
while(Q->next!=top)//get to the last node
{
Q=Q->next;
}
cout<<"Q next is top now"<<endl;
Q->next=N;
N->prev=Q;
N->next=top;
top->prev=N;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这段代码有一些问题。首先,如果你要频繁地执行“insertAfterLast”,则应该使用“top->prev”来获取指向恒定时间内最后一个元素的指针;否则构建列表将需要二次 (O(n^2)) 时间。其次,在任何实际项目中,从头开始实现循环链表几乎肯定是一个坏主意 - 相反,您想坚持使用成熟的 STL 兼容容器,例如 std::deque 或 Boost 的 circular_buffer。
假设您确实想这样做,并且您不关心空列表,那么上面的函数似乎已经完全正确。最有可能的问题是开始之前的初始列表格式错误,或更可能的是,当您迭代列表以在最后打印出来时,您跳过了最后一个元素。迭代循环链表的正确方法如下(改编自 Wikipedia):
This code has a few issues. First, if you're going to do "insertAfterLast" frequently, you should use "top->prev" to get a pointer to the last element in constant time; otherwise building a list will require quadratic (O(n^2)) time. Second, in any real project implementing a circular linked list from scratch is almost certainly a bad idea - instead you want to stick with a mature STL-compliant container like std::deque or Boost's circular_buffer.
Assuming you really do want to do this, and you're not concerned about empty lists, your function above appears to already be completely correct. Most likely the problem is either that your initial list before you begin is malformed, or more likely, that when you iterate over the list to print it out at the end, you're skipping the last element. The right way to iterate over a circularly linked list is like this (adapted from Wikipedia):