编写一个类,实现简单的栈(提示:可用链表实现)。数据的操作按先进后出(FILO)的顺序。

头文件:

#include<iostream>
using namespace std;

class Queue
{
public:
	void put(int item);//在链表结尾插入节点
	int get();//取出一个节点
	void print();//打印剩余的节点
};

 定义成员函数:

#include"queue.h"
#include<iostream>
using namespace std;
struct Data
{
	int t;
	Data* next;
};
Data* head;
Data* cur = head;//当前
Data* pre;//前一个
int cnt = 0;//用于判断是否是第一次定义链表
void Queue::put(int item)
{
	cur = new Data;
	cur->t = item;
	if (cnt == 0)//head
	{
		cur->next = NULL;
		pre = cur;
		head = cur;//第一个节点赋值给head
		cnt++;
	}
	else
	{
		cur->next = NULL;//当前节点为链表结尾
		pre->next = cur;//前一个节点的后继之中指向当前的节点
		pre = cur;//当前节点成为前一个节点
	}
}
int Queue::get()
{
	int result;
	for (Data* cur = head; cur != NULL; cur = cur->next)
	{
		Data* after = cur->next;//当前节点的下一个节点
		if (after->next == NULL)//如果下一个节点为链表结尾
		{
			result = after->t;
			cur->next = NULL;//当前节点成为链表结尾
			delete after;
		}
	}
	return result;
}
void Queue::print()
{
	cout << "栈中剩余 ";
	for (Data* cur = head; cur != NULL; cur = cur->next)
	{
		cout << cur->t;
		if (cur->next != NULL)//除了最后一个,其他数字后面都加上‘、’
		{
			cout << "、";
		}
	}
	cout << endl;
}

 调用成员函数:

#include"queue.h"
#include<iostream>
using namespace std;

int main()
{
	Queue que;
	que.put(10);
	que.put(12);
	que.put(14);
que.print();
	cout << "取出:" << que.get() << ",";
	que.print();
	cout << "取出:" << que.get() << ",";
	que.print();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值