[英]adding node at last in Linked List in C++
我试图实现单链接列表。 我的addAtLast()函数未正确执行。 执行此功能时程序崩溃。 请提出一些变化。
class LList
{
public:
int noOfNodes;
Node const *start;/*Header Node*/
LList()
{
start=new Node;
noOfNodes=0;start=0;
}
void addAtFront(Node* n)
{
/*
cout<<endl<<"class"<<n;
cout<<"start"<<start;
cout<<"data in node";n->print();
*/
n->next=const_cast<Node*>(start);
start=n;
// cout<<" next=";start->print();
noOfNodes++;
}
void addAtLast(Node* n)
{
Node *cur=const_cast<Node*>(start);
if (start==NULL)
{
start=n;
return;
}
while(cur->next!=NULL)
{
cur=cur->next;
}
cur->next=n;
noOfNodes++;
}
int getPosition(Node data)
{
int pos=0;
Node *cur=const_cast<Node*>(start);
while(cur!=NULL)
{
pos++;
if(*cur==data)
{
return pos;
}
cur=cur->next;
}
return -1;//not found
}
Node getNode(int pos)
{
if(pos<1)
return -1;// not a valid position
else if(pos>noOfNodes)
return -1; // not a valid position
Node *cur=const_cast<Node*>(start);
int curPos=0;
while(cur!=NULL)
{
if(++curPos==pos)
return *cur;
cur=cur->next;
}
}
void traverse()
{
Node *cur=const_cast<Node*>(start);
while(cur!=NULL)
{
// cout<<"start"<<start;
cur->print();
cur=cur->next;
}
}
~LList()
{
delete start;
}
};
void addAtLast(Node* n) {
Node *cur=const_cast<Node*>(start);
if(start==NULL) {
start=n;
n->next = NULL;
noOfNodes++;
return;
}
while(cur->next!=NULL) {
cur=cur->next;
}
cur->next=n;
n->next = NULL; // Added
noOfNodes++;
}
从一开始就..
start=new Node;
noOfNodes=0;start=0;
应该这样吗?
start=new Node;
noOfNodes=0;start->next=NULL;
在2行中,您创建了内存泄漏。 我不知道您为什么要设置start=0
。 不要那样做,您已经为其分配了内存!
至于崩溃,可以通过@liulinhuai的答案解决。 您将取消引用未初始化的指针,尝试获取它的next
成员。
在您的ctor中,将start设置为0。在崩溃函数中,您首先检查它是否为NULL
:
if (start==NULL)
{
start=n;
//n->next is now points to nowhere
return;
}
下次调用addAtLast
进行迭代,直到找到NULL
但是上一个addAtLast
没有将next
指针设置为NULL
因此第二次迭代将导致access violation
:
while(cur->next!=NULL) {
//first time it's ok but second call on cur will crash
cur=cur->next;
}
解决方案是-所有新Node
必须将next
指针设置为NULL
我提到了此评论,但将在此处作为答案解决。 此函数的调用者必须确保两件事:
必须将传入的节点列表(即使只有一个元素长, 也是一个列表)也必须通过将end-next-pointer设置为NULL来正确终止。 调用者必须确保这一点,因为此代码无法假定它,并且盲目将node->next = NULL;
设置node->next = NULL;
绝对确保调用者知道,一旦这个执行, 这个名单现在拥有传入的节点和任何列表它可能开始与主叫方,因此,决不能释放它,或任何其指向,对发送方。
除了节点数管理问题之外, addAtLast()
函数没有任何问题,尽管我会以不同的方式实现它:
void addAtLast(Node* n)
{
// no nulls allowed
if (n == NULL)
return;
// set start if first in list
if (start == NULL)
{
start = n;
noOfNodes = 1;
}
// else walk list to find end
else
{
Node *cur = const_cast<Node*>(start);
while(cur->next != NULL)
cur = cur->next;
cur->next = n;
++noOfNodes;
}
// adjust count to contain any nodes from 'n'
while (n->next != NULL)
{
++noOfnodes;
n = n->next;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.