【发布时间】:2016-10-29 16:40:06
【问题描述】:
这是一个程序,它从用户那里获取学生姓名和注册号,并将其存储在双向链表中。我在最后插入节点。但是在while循环中有一个逻辑错误。它需要名称和注册。编号但随后停止。请帮助
class dlist{
struct node{
string name;
string regno;
node *next;
node *prev;
};
public:
node *head,*tail;
void insert(string,string);
void search(string);
};
void dlist::insert(string nn, string r)
{
node *ptr,*newNode;
tail=head;
newNode= new node;
newNode->name=nn;
newNode->regno=r;
newNode->next=NULL;
newNode->prev=NULL;
if(!head)
{
head=newNode;
tail=head;
}
else
{
ptr = head;
while(ptr)
ptr=ptr->next;
newNode->next=tail;
newNode->prev=ptr;
ptr->next-newNode;
}
}
void dlist::search(string n){
node *ptr;
ptr=head;
while(ptr->next!=NULL)
{
if(ptr->name==n)
cout<<"Name found..." <<ptr->name<<endl;
ptr=ptr->next;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
dlist dl;
string nn;
string n;
string r;
for(int i=0;i<5;i++)
{
cout<<"Enter student's name: ";
cin>>nn;
cout<<"Enter student's Registration Number: ";
cin>>r;
dl.insert(nn,r);
}
cout<<"Enter a name to search: ";
cin>>n;
dl.search(n);
}
【问题讨论】:
-
ptr->next-newNode什么都不做......而且我们没有完整的源代码,所以我们无法帮助您(而是minimal reproducible example)。虽然这听起来很可疑:ptr->next = ptr->prev -
好的,我认为这可能有助于理解。对此感到抱歉。让我编辑
-
你为什么要设置
tail=head?? -
我希望我在最后一个节点有一个链接,所以我使用了一个指针 tail.. 就像那时 newNode->next=tail
-
我可以不用尾指针吗? else部分的while循环有问题。我想不出更好的解决方案
标签: c++ linked-list doubly-linked-list