#include<iostream>
using namespace std;
class Node //定义一个Node类
{
public:
int id, age; //数据域
class Node *next; //指针域
class Node* create1();//创建链表函数1
class Node* create2();//创建链表函数2
};
int n; //统计节点个数
class Node* Node::create1()
{
class Node *p1, *p2, *head;
p1 = p2 = new class Node;
cout << "输入0 0停止创建"<<endl;
cin >> p1->id >> p1->age;
head = NULL;
n = 0;
while (p1->id != 0)
{
n = n + 1;
if (n == 1){
head = p1;
}
else{
p2->next = p1;
}
p2 = p1;
p1 = new class Node;
cin >> p1->id >> p1->age;
}
p2->next = NULL;
delete p1;
return head; //返回一个class Node* 类型的指针变量
}
class Node* Node::create2()
{
int x, y;
class Node *head, *p, *r, *pr;
head = new class Node;
cout << "输入0 0停止创建"<<endl;
cin >> x >> y;
r = head;
while (x > 0)
{
p = new class Node;
p->id = x;
p->age = y;
p->next = NULL;
r->next = p;
r = p;
cin >> x >> y;
}
head = head->next;
return head;
}
void main()
{
class Node a; //定义对象a
class Node *pt, *temp; //pt遍历指针,temp跟班指针
pt =a. create1();
//pt = a.create2();
while (pt != NULL)
{
cout << pt->id << "\t" << pt->age << "\n";
pt = pt->next;
}
}
【C++】用类的方式创建链表
最新推荐文章于 2024-08-19 23:23:47 发布