如何使用 class 获得链表?
How can I have a linked-list using class?
我正在尝试使用 class 编写链表,我希望它具有特定格式。
例如,如果我有三个名为 p1、p2 和 p3 的数据以及一个名为 list 的链表;我想把它们整理得井井有条。
list.insert(p1).插入(p2).插入(p3);
我尝试 return 该对象,但没有成功。
这是我的代码。
#include<iostream>
using namespace std;
class linked_list {
public:
int *head;
linked_list();
~linked_list();
linked_list insert(int data);
};
linked_list::linked_list()
{
head = NULL;
}
linked_list::~linked_list()
{
int *temp;
int *de;
for (temp = head;temp != NULL;) {
de = temp->next;
delete temp;
temp = de;
}
delete temp;
//delete de;
}
linked_list linked_list::insert(int data)
{
int *temp;
temp = new int;
*temp = data;
temp->next = NULL;
if (head == NULL) {
head = temp;
}
else {
int* node = head;
while (node->next != NULL) {
node = node->next;
}
node->next = temp;
// delete node;
}
//delete temp;
return *this;
}
int main(){
linked_list l1;
int p1,p2,p3;
l1.insert(p1).insert(p2).insert(p3);
return 0;}
@Jarod42 得到了你的答案,尽管周围有很多错误的东西,但你想要的是这样的东西。
您要链接的函数必须 return 对您当前对象实例的引用。
这是一个 Foo
class 多次更改其 _data
成员和链。
#include <iostream>
class Foo
{
private:
int _data;
public:
Foo(int data) : _data(data) {}
~Foo()
{
}
// change the value of data then return a reference to the current Foo instance
Foo &changeData(int a)
{
_data = a;
return *this;
}
void printData()
{
std::cout << _data << std::endl;
}
};
int main()
{
Foo f(1);
f.changeData(2).changeData(3);
f.printData();
}
请注意,我正在 returning Foo&
来自我链接的函数,这是你的函数缺少的小技巧。
希望对您有所帮助:)
我正在尝试使用 class 编写链表,我希望它具有特定格式。
例如,如果我有三个名为 p1、p2 和 p3 的数据以及一个名为 list 的链表;我想把它们整理得井井有条。
list.insert(p1).插入(p2).插入(p3);
我尝试 return 该对象,但没有成功。 这是我的代码。
#include<iostream>
using namespace std;
class linked_list {
public:
int *head;
linked_list();
~linked_list();
linked_list insert(int data);
};
linked_list::linked_list()
{
head = NULL;
}
linked_list::~linked_list()
{
int *temp;
int *de;
for (temp = head;temp != NULL;) {
de = temp->next;
delete temp;
temp = de;
}
delete temp;
//delete de;
}
linked_list linked_list::insert(int data)
{
int *temp;
temp = new int;
*temp = data;
temp->next = NULL;
if (head == NULL) {
head = temp;
}
else {
int* node = head;
while (node->next != NULL) {
node = node->next;
}
node->next = temp;
// delete node;
}
//delete temp;
return *this;
}
int main(){
linked_list l1;
int p1,p2,p3;
l1.insert(p1).insert(p2).insert(p3);
return 0;}
@Jarod42 得到了你的答案,尽管周围有很多错误的东西,但你想要的是这样的东西。
您要链接的函数必须 return 对您当前对象实例的引用。
这是一个 Foo
class 多次更改其 _data
成员和链。
#include <iostream>
class Foo
{
private:
int _data;
public:
Foo(int data) : _data(data) {}
~Foo()
{
}
// change the value of data then return a reference to the current Foo instance
Foo &changeData(int a)
{
_data = a;
return *this;
}
void printData()
{
std::cout << _data << std::endl;
}
};
int main()
{
Foo f(1);
f.changeData(2).changeData(3);
f.printData();
}
请注意,我正在 returning Foo&
来自我链接的函数,这是你的函数缺少的小技巧。
希望对您有所帮助:)