【发布时间】:2021-03-24 05:31:13
【问题描述】:
#include <iostream>
#include <string>
using namespace std;
class Node{
public:
double data;
Node* next;
Node* prev;
};
void insert(Node**,int);
void display(Node*);
void finaloutput(Node*,Node**);
int main()
{
Node* head=NULL;
Node** second=NULL;
insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,4);
insert(&head,5);
cout<<"List is"<<endl;
display(head);
cout<<endl;
cout<<"Final output is"<<endl;
second=&head;
// Node* second=(*&head);
finaloutput(head,second);
display(head);
}
void insert(Node** headref,int new_data)
{
Node* new_node=new Node();
new_node->data=new_data;
new_node->next=(*headref);
new_node->prev=NULL;
if(*headref!=NULL)
{
(*headref)->prev=new_node;
}
(*headref)=new_node;
}
void display(Node* headref)
{
Node* temp=headref;
while (temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
void finaloutput(Node* headref,Node** second)
{
Node ptrbegin;
Node* temp=(headref);
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=(*second);
}
我想创建一个函数来在最后向自身添加一个链接列表,但在temp->next=(*second) 之后,这最终显示了一个无限循环。我试图将Node* head 的唯一值副本作为second,但它没有帮助。请用 c++ 中的示例代码指导我。
我想要的输出就像 '5 4 3 2 1 5 4 3 2 1'
【问题讨论】:
-
您需要在
display函数中添加一些条件才能停止,因为如果您将最后一个节点与第一个节点链接,它是一个循环列表,display中的while (temp!=NULL)将始终返回true因此无限循环。另外,我不明白所需的输出,中间的额外“4”来自哪里? -
@Arsam Javed 为什么在这个预期的输出 5 4 3 2 1 4 5 4 3 2 1 中有三个数字 4?
-
抱歉我的错误现在已更正
标签: c++ struct doubly-linked-list function-definition