数组实现:

#include <iostream>
#include <string>
using namespace std;
typedef string T;

class Stack{
    T a[5];
    int cur;
public:
    Stack():cur(0){}
    void push(const T& d)throw(const char*);//如栈
    T pop()throw(const char*);//出栈
    const T& top()const throw(const char*);//取得栈顶数据
    bool empty()const{return cur==0;}//是否是空栈
    bool full()const{return cur==5;}//是否已满
    void clear(){cur=0;}
    int size()const{return cur;}
};

void Stack::push(const T& d)throw(const char*)
{
    if(full()) throw "满";
    a[cur++] = d;
}
T Stack::pop()throw(const char*)
{
    if(empty()) throw "空";
    return a[--cur];
}
const T& Stack::top()const throw(const char*)
{
    if(empty()) throw "空";
    return a[cur-1];
}

int main()
{
    Stack s;
	try{
	s.push("芙蓉");
	s.push("凤姐");
	s.push("春哥");
	s.push("曾哥");
	s.push("权哥");
	s.push("犀利");
	}
	catch(const char* e){
		cout << "异常:" << e << endl;
	}
	while(!s.empty()){
		cout << s.pop() << endl;
	}
}

链表实现:

01list.h

#ifndef LIST_H
#define LIST_H 1
class List{
	struct Node{
		T 		data;
		Node* 	next;
		Node* 	prev;
		Node(const T& d=T()):data(d),next(0){}//零初始化
	};
	Node* head;//头指针,用来保存头节点的地址
	int len;
	public:
	List():head(NULL),len(0){ }
	void push_front(const T& d);//前插
	List& push_back(const T& d);//尾插
	int size()const;
	Node*& getptr(int pos);//找链表中指向指定位置的指针
	void insert(const T& d, int pos);//在任意位置插入
	void travel()const;//遍历
	void clear();//清空这个链表
	~List();
	void erase(int pos);//有效位置为0~size()-1
	void remove(const T& d);
	int find(const T& d)const;
	void set(int pos, const T& d);
	bool empty()const{return head==NULL;}
	const T& front()const{if(empty())throw "空";return head->data;}
	const T& back()const;
};
#endif


#include <iostream>
using namespace std;
typedef int T;
#include "01list.h"//链表
class Stack{
	List l;
public:
	void push(const T& d);//数据入栈成为栈顶
	T pop();//栈顶数据出栈,下一个数据成为栈顶
	const T& top()const;//取得栈顶数据
	bool empty()const{return l.empty();}//是否空栈
	bool full()const{return false;}//是否已满
	void clear(){l.clear();}//栈清空(复位)
	int size()const{return l.size();}//栈中数据个数
};
void Stack::push(const T& d){
	l.push_front(d);
}
T Stack::pop(){
	T t = l.front();
	l.erase(0);
	return t;
}
const T& Stack::top()const {
	return l.front();
}
int main()
{
	Stack s;
	try{
	s.push(1);
	s.push(2);
	s.push(3);
	s.push(4);
	s.push(5);
	s.push(6);
	}
	catch(const char* e){
		cout << "异常:" << e << endl;
	}
	while(!s.empty()){
		cout << s.pop() << endl;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值