【C++】用类的方式创建链表

#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;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C++小白、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值