C++类的应用举例(编写类 queue ,实现简单的栈)

1. 编写类 queue ,实现简单的栈(FILO,先进后出)

 用于存放整型变量

 成员变量包括:

 头节点

 成员函数包括:

 void push(int item); //将整型 item 压入栈中

 int pop(); //从栈中弹出一个数据

 int count(); //统计当前栈中的数据个数

 bool empty(); //判断栈是否为空

#include<iostream>
#include<stdlib.h>
#include<windows.h>
using namespace std;
template<class T>class queue
{
private:
	struct Node
	{
		T data;
		Node* next;
	};
	Node* head;
	Node* p;	
public:
	int length;
	queue()
	{
		head = NULL;
		length = 0;
	}
	void push(T n)//入栈
	{
		Node* q = new Node;
		q->data = n;
		if (head == NULL)
		{
			q->next = head;
			head = q;
			p = q;
		}
		else
		{
			q->next = p;
			p = q;
		}
		length++;
	}
	T pop()//出栈并且将出栈的元素返回
	{
		if (length <= 0)
		{
			abort();
		}
		Node* q;
		T data;
		q = p;
		data = p->data;
		p = p->next;
		delete(q);
		length--;
		return data;
	}
	void count()//返回元素个数
	{
		 cout << length;
	}
	bool isEmpty()//判断栈是不是空的
	{
		if (length == 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	void clear()//清空栈中的所有元素
	{
		while (length > 0)
		{
			pop();
		}
	}
};
int main()
{
	queue<char> q;
	q.push('a');
	q.push('b');
	q.push('c');
	cout << "栈的元素有:" ;
	q.count(); cout << endl;
	cout << "出栈元素分别为:" << endl;
	while (!q.isEmpty())
	{
		
		cout << q.pop() << endl;
	}
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值