顺序表实现:

#include<iostream>
#include<stdexcept>
using namespace std;

template<typename T>

class Stack {
private:
	T* data;//T类型的数组
	int size;//元素个数
	int capacity;//容量
	void resize();//扩容函数
public:
	Stack():data(new T[capacity]),size(0),capacity(10){}
	~Stack() {};
	void push(T element);//增
	T pop();//弹出元素
	T top() const ;//获取一个元素
	int getSize()const;
};

template<typename T>
void Stack<T>::resize() {
	int newCapacity = capacity * 2;
	T* newData = new T[capacity];
	for (int i = 0; i < size; i++) {
		newData[i] = data[i];
	}
	delete data;
	data = newData;
	capacity = newCapacity;
}

template<typename T>
void Stack<T>::push(T element) {
	if (size == capacity) {
		resize();//如果元素个数等于实际容量,也就是满了,则扩容
	}
	data[size++] = element;//堆栈
}

template<typename T>
T Stack<T>::pop() {
	if (size == 0) {
		throw std::underflow_error("栈为空");
	}
	return data[--size];//返回弹出的值
}

template<typename T>
T Stack<T>::top() const{
	if (size == 0) {
		throw std::underflow_error("栈为空");
	}
	return data[size - 1];//返回顶部的值
}

template<typename T>
int Stack<T>::getSize() const {
	return size;//返回大小
}

测试用例:

int main() {
	Stack<int> st;
	st.push(4);
	st.push(7);
	st.push(13);
	cout << st.top() << endl;
	st.push(17);
	cout << st.top() << endl;
	st.pop();
	st.pop();
	cout << st.top() << endl;

	return 0;
}

链表实现:

#include<iostream>
#include<stdexcept>
using namespace std;

template<typename T>
class Stack {
private:
	struct Node {
		T data;//数
		Node* next;//后继节点
		Node(T d):data(d),next(NULL){}//初始化
	};
	Node* head;//头节点
	int size;//元素个数
public:
	Stack() :head(NULL), size(0) {};
	~Stack();
	void push(T element);
	T pop();
	T top()const;
	int getSize()const;
};

template<typename T>
Stack<T>::~Stack() {
	while (head) {
		Node* temp = head;//缓存
		head = head->next;//遍历
		delete temp;//删除
	}
}

template<typename T>
void Stack<T>::push(T element) {
	Node*newNode = new Node(element);//创建新节点
	newNode->next = head;//插入到头节点后方
	head = newNode;//成为新的头节点
	size++;
}

template<typename T>
T Stack<T>::pop() {
	if (head == NULL) {
		throw std::underflow_error("栈为空");
	}
	T result = head->data;
	Node* temp = head;//因为要删除旧head但又要使用它,所以先缓存
	head = head->next;//head向下移动
	delete temp;//删除原来的head;
	size--;
	return result;
}

template<typename T>
T Stack<T>::top()const {
	if (head == NULL) {
		throw std::underflow_error("栈为空");
	}
	return head->data;
}

template<typename T>
int Stack<T>::getSize()const {
	return size;
}

测试用例:

int main() {
	Stack<int>st;
	st.push(4);
	st.push(7);
	st.push(13);
	cout << st.top() << endl;
	st.push(17);
	cout << st.top() << endl;
	st.pop();
	st.pop();
	cout << st.top() << endl;
}

更多推荐