C++ 写栈 和 队列

栈的代码, 比较容易实现:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
class Point{
public:
	int x, y;
	Point(int x, int y):x(x), y(y){}
	Point(){}
};
template<class T>
class Stack{
public:
	Stack(){
		cur = 0;
	}
private: 
	T s[1000];
	int cur;
public:	
	void push(T t){
		s[cur++] = t;
	}
	T top(){
		return s[cur - 1];
	}
	void pop(){
		cur--;
	}
};

int main()
{
	Stack<Point>s;
	s.push(Point(1, 2));
	s.push(Point(4, 5));
	//s.pop();
	cout << s.top().x << endl;
	return 0;
}

队列的代码, 有链表实现:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;

class Node{
public:
	Node *next;
	Node *pre;
	int t;
	Node(){
		next = NULL;  //这两个都得是NULL
		pre = NULL;
	}
	Node(int t):t(t){
	}
};
template<class T>
class Link{
public:
	T *head;          //指向队列头
	T *tell;          //指向队列尾
	int len;
	Link(){
		head = new T(); //一开始为脑袋实例化, 注意head里面不存数据, 只是标识队列
		tell = NULL;    //一开始尾巴为空
		len = 0;
	}
	void insert(T t){
		T *newT = new T();
		*newT = t;              //为声明的空间赋值, 这里需要重载T的赋值符号=
		
		//让老二和newT关联
		T *tmp = head->next;
		newT->next = tmp;
		if(NULL != tmp)  //如果没有老二
			tmp->pre = newT;

		//让新的老二和脑袋关联
		head->next = newT;
		newT->pre = head;
		//当长度为0的时候就更新tell的指向
		if(0 == len){    
			tell = newT;
		}
		len++;
	}
	T front(){
		if(0 == len)
			return NULL;
		return *tell;
	}
	void pop(){
		if(0 == len){
			tell = NULL;
			return;
		}
		else{      //删除尾指针所指向的空间后更新尾指针的指向
			T *tmp = tell->pre;
			delete tell;
			tell = tmp;
			len--;
		}
	}
	bool empty(){
		return 0 == len;
	}

};

int main(){
	Link<Node>l;
	l.insert(Node(12));
	l.insert(Node(23));
	l.insert(Node(27));
	l.pop();
	l.pop();
	l.pop();
	if(!l.empty())
		cout << l.front().t << endl;
	else{
		cout << "l is empty" << endl;
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值