【发布时间】:2019-03-09 06:55:21
【问题描述】:
我正在练习插入双向链表。我不知道为什么这段代码不能正常工作。这段代码的输出是:
position doesn't exist
position doesn't exist
1
2
如您所见,它甚至没有打印第三个数据。我知道我做错了什么,但我无法在这段代码中找出我的错误。请帮帮我。
#include <iostream>
using namespace std;
struct dllnode
{
int data;
dllnode *next,*prev;
};
class dlinked_list
{
dllnode *head,*tail;
public:
dlinked_list() //Constructor
{
head=NULL;
tail=NULL;
}
void insertionindll(int ,int);
static void display(dllnode *);
dllnode* gethead()
{
return head; //returning head pointer of the linkedlist
}
dllnode* create_node(int data);
};
dllnode* dlinked_list::create_node(int n) //Creating a new node
{
dllnode *temp=new dllnode;
temp->data=n;
temp->prev=NULL;
temp->next=NULL;
return temp; //returning the address of the newly created node to line no. 39
}
void dlinked_list::insertionindll(int n, int pos)
{
dllnode *temp;
int k=1;
dllnode *newnode= create_node(n); //storing address of the newly created node
if(!newnode)
{
cout<<"Memory Error"; //Checking memory error
return;
}
newnode->data=n;
if(pos==1) //Insertion at the beginning//
{
newnode->next=head;
newnode->prev=NULL;
if(head) //checking if head!=NULL
head->prev=newnode;
head=newnode; //now head points to the newly created node
return;
}
temp=head; //temp is now pointing to the first node
//After this loop temp will either point to the last node
//or the previous node at which we want to insert newnode
while(k<pos && temp->next!=NULL)
{
k++; //incrementing k
temp=temp->next;
}
if(k!=pos) //checking if the position doesn't exist
{
cout<<"position doesn't exist"<<endl;
}
newnode->prev=temp;
newnode->next=temp->next;
if(temp->next)
temp->next->prev=newnode;
temp->next=newnode;
return;
}
void dlinked_list::display(dllnode *a) //for displaying the created linked list
{
dllnode *ptr; //declaring a pointer which points to the head of the linked list
ptr=a;
while(ptr->next!=NULL) //iterating untill the last node
{
cout<<ptr->data<<endl; //printing data of the linked list
ptr=ptr->next; //pointng to the next node
}
return;
}
int main()
{
/* code */
dlinked_list a; //creating an object a of class dlinked_list
a.insertionindll(1,1); //here insertionindll function is called
a.insertionindll(2,2);
a.insertionindll(3,3);
dlinked_list::display(a.gethead()); //display function is called by passing head pointer
return 0;
}
【问题讨论】:
-
当您使用调试器一次执行一行程序时,并且在您使用调试器检查所有变量的值之后,在程序的每一行执行后,观察到了什么你做的?
-
建议:不要使用
create_node方法,而是让dllnode构造函数更智能。例如:dllnode (int indata) : data(indata), prev(NULL), next(NULL) {}。另一个建议:if(!newnode)在使用new创建节点后是不必要的。new如果失败则抛出异常,保证你永远不会到达这里(除非你改变了new的行为,这是一个你暂时不应该搞砸的高级主题)。 -
在没有先确定
ptr不是NULL的情况下,认真思考为什么while(ptr->next!=NULL)测试ptr->next。 -
感谢您关于内存检查@user4581301 的第二个建议,是的,显示功能的while 循环中存在问题。它应该是:while(ptr!=NULL) 但我不明白你关于更聪明的构造函数的观点。我认为只有在我们创建任何对象时才会调用构造函数。就我而言,我正在处理一个列表,那么如果我删除 create_node 方法,它如何帮助创建一个新节点?我的意思是每次需要从主函数创建新节点时如何调用构造函数?