C++ 练习使用重载操作符封装Iterator

学过链表和重载操作符之后,我们就可以写一个链表的迭代器,方便我们使用链表。

原链表:

//链表节点结构体
struct Node
{
	int val;
	Node* next;
	Node(int n) {
		val = n;
		next = nullptr;
	}
};
class myList {
public:
	Node* pHead;
	Node* pEnd;
	int nLen;
	myList() {
		pHead = nullptr;//初始化头空
		pEnd = nullptr;//初始化尾空
		nLen = 0;//初始化长度为0
	}
	~myList() {//与销毁函数一致
		Node* tmp = nullptr;//定义标记指针
		while (pHead)
		{
			tmp = pHead;//标记当前头
			pHead = pHead->next;//头偏移到下一个
			delete tmp;//回收标记的老头
			tmp = nullptr;//标记指针赋空
		}
		nLen = 0;//长度归0
		pHead = nullptr;//头指针赋空
		pEnd = nullptr;//尾指针赋空
	}


	//从后面插入
	void push_back(int n) {
		Node* node = new Node(n);//申请新的节点
		if (pHead == nullptr) pHead = node;//如果是空链表新元素就是表头
		else pEnd->next = node;//否则让尾指向新节点
		pEnd = node;//新节点成为新的尾
		++nLen;//长度+1
	}
	//从前面删除
	void pop_front() {
		Node* tmp = pHead;//标记头
		pHead = pHead->next;//头偏移到下一个
		//如果pHead偏移完为空说明链表没有元素了pEnd也赋值空
		if (pHead == nullptr)pEnd = nullptr;
		delete tmp;//删除标记的老头
		tmp = nullptr;//标记指针赋空
		--nLen;//长度-1
	}
	//遍历链表
	void show_List() {
		Node* tmp = pHead;//标记头
		//遍历
		while (tmp) {
			cout << tmp->val << " ";
			tmp = tmp->next;
		}
		cout << endl;//换行
		tmp = nullptr;//标记指针赋空
	}
	//返回链表长度
	int list_Len() {
		return nLen;
	}
	//销毁链表
	void destoryList() {
		Node* tmp = nullptr;//定义标记指针
		while (pHead)
		{
			tmp = pHead;//标记当前头
			pHead = pHead->next;//头偏移到下一个
			delete tmp;//回收标记的老头
			tmp = nullptr;//标记指针赋空
		}
		nLen = 0;//长度归0
		pHead = nullptr;//头指针赋空
		pEnd = nullptr;//尾指针赋空
	}

};

对遍历这个功能分析能改进的地方

赋值---operator=,判断是否相等operator== operator!=,间接引用取值 operator*,向后移动 operator++。

//遍历链表
void show_List() {
	Node* tmp = nullptr;
    tmp = pHead;//赋值 ,operator=
	//遍历
	while (tmp) {//判断是否等于、不等于某个节点 operator== operator!=
		cout << tmp->val << " ";// 间接引用取值 operator*
		tmp = tmp->next;    //向后移动 operator++
	}
	cout << endl;
	tmp = nullptr;
}

设计迭代器类

class CMyIterator {
public:
	Node* tmp;
	CMyIterator() {
		tmp = nullptr;
	}
	CMyIterator(Node* node) {
		tmp = node;
	}
	~CMyIterator() {}
public:
	Node* operator=(Node* node) {
		tmp = node;
		return node;
	}
	bool operator==(Node* node) {
		return tmp == node;
	}
	bool operator!=(Node* node) {
		return tmp != node;
	}
	int operator*() {
		if (tmp) {
			return tmp->val;
		}
		return -1;
	}
	Node* operator++() {
		if (tmp) {
			tmp = tmp->next;
		}
		return tmp;
	}
	Node* operator++(int) {
		Node* m = tmp;
		if (tmp) {
			tmp = tmp->next;
		}
		return m;
	}

};

使用迭代器改造后的遍历

//遍历链表
	void show_List() {
		CMyIterator ite = pHead;
		while (ite != nullptr) {
			cout << *ite << " ";
			ite++;
		}
		cout << endl;//换行
	}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值