才开始学数据结构,复现单链表的时候出现问题。。。
当我打算在头结点后面再创一个值为1的结点时,输出结果显示链表长度增加1,但是不能输出新增结点的属性,代码如下,求大佬解答
#include<iostream>
using namespace std;
struct LinkNode { //链表结点
int data;
LinkNode* link;
LinkNode()
{
this->link = NULL;
this->data = 0;
}
LinkNode(const int& data, LinkNode* link = NULL)
{
this->data = data;
this->link = link;
}
};
class Link :public LinkNode { //单链表
private:
LinkNode* first;
public:
Link()
{
first = new LinkNode;
}
Link(const int& d)
{
first = new LinkNode(d);
}
int lenth(); //返回列表长度
LinkNode* Locate(int i); //定位
bool Create(int d); //创造一个新结点
};
LinkNode* Link::Locate(int i)
{
if (i < 0)
{
return false;
}
int count = 0;
LinkNode* current = first;
while (count < i&¤t->link!=NULL)
{
current = current->link;
count++;
}
return current;
}
int Link::lenth()
{
int lenth = 0;
LinkNode* current = first;
while (current->link != NULL)
{
lenth++;
current = current->link;
}
return lenth;
}
bool Link::Create(int d)
{
LinkNode* current = Locate(lenth());
LinkNode* newnode = new LinkNode(d);
if (newnode == NULL && current == NULL)
{
cout << "存储分配错误" << endl;
exit(1);
}
current->link = newnode;
return true;
}
int main()
{
Link* a = new Link;
cout << a->data << ' ' << a->lenth() << endl;
a->Create(1); //创建一个值为1的结点
cout << a->lenth() << endl;
cout << a->link->data;
return 0;
}