C++实现带头结点的单链表(友元类)

代码实现 单链表的头插和尾插   

#include <iostream>
using namespace std;

class Node
{
	public:
		Node(int data, Node* next = NULL)//构造函数
		{
			mdata = data;
			pnext = next;
		} 
		//不用写析构函数 因为头结点是在栈上开辟的 
		//不需要手动去释放 所以不写析构函数
	private:
		int mdata;
		Node* pnext;
	/*
		友元关系
		破坏封装性
		C++ 能不用友元 尽量不要用
	*/
	/*
		
		List是Node的友元类
	*/
	friend class List;
};
class List
{
	public:
	/*
		构造函数后加上一个冒号
		初始化列表给编译给出了成员变量的初始化方式
		Node phead(0)
	*/
	/*
		初始化成员变量的顺序和初始化列表中的顺序是没有关系
		和成员变量的声明顺序有关
	*/
		List():phead(0)
		{
		}
		void InsertHead(int data)
		{
			Node* pNewNode = new Node(data);
			pNewNode->pnext = phead.pnext;
			phead.pnext = pNewNode;
		}
		void InsertTail(int data)
		{
			Node* pNewNode = new Node(data);
			Node* pCur = &phead;
			while (pCur->pnext != NULL)
			{
				pCur = pCur->pnext;
			}
			pCur->pnext = pNewNode;
		}
	/*
		this  ==>  const List*const
	*/
		void Show()const
		{
			Node* pCur = phead.pnext;
			Node* pNext = pCur;
			while (pCur != NULL)
			{
				pNext = pCur->pnext;
				cout << pCur->mdata << " ";
				pCur = pNext;
			}
			cout << endl;
		}
		~List()
		{
			Node* pCur = phead.pnext;
			Node* pNext = pCur;
			while (pCur != NULL)
			{
				pNext = pCur->pnext;
				delete pCur;
				pCur = pNext;
			}
			phead.pnext = NULL;
		}
	private:
		Node phead;//成员对象
};

int main()
{
	List list1;
	List list2;

	for (int i = 0; i < 10; ++i)
	{
		list1.InsertHead(i + 1);
		list2.InsertTail(i + 1);
	}

	cout << "list1:";
	list1.Show();
	cout << endl;
	
	cout << "list2:";
	list2.Show();

	return 0;
}

运行结果:


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值