小言_互联网的博客

c++顺序表实现栈

419人阅读  评论(0)

通过capacity控制最大容量,超过就扩容,可以避免多次插入时的扩充操作 

template<class T>
class Stack {
public:
	Stack();
	Stack(const size_t & length);
	Stack(const Stack<T> & s);
	~Stack();
	void push(const T & elem);
	void pop();
	const T & top() const { return empty() ? NULL : m_elem[m_top]; }
	size_t size() const { return m_top + 1; }
	size_t capacity() const { return m_capacity; }
	bool empty() const { return -1 == m_top; }
private:
	T *m_elem; // 栈内元素储存的地方
	size_t m_capacity; // 最大容量
	int m_top; // 栈头指针
};

template<class T>
Stack<T>::Stack()
{
	m_elem = nullptr;
	m_capacity = 0;
	m_top = -1;
}

template<class T>
Stack<T>::Stack(const size_t & length)
{
	m_elem = new T[length];
	m_capacity = length;
	m_top = -1;
	memset(m_elem, NULL, sizeof(m_elem));
}

template<class T>
Stack<T>::Stack(const Stack<T>& s)
{
	m_elem = new T[s.size()];
	m_capacity = s.m_capacity;
	m_top = s.m_top;
	for (size_t i = 0; i < m_capacity; ++i) {
		m_elem[i] = s.m_elem[i];
	}
}

template<class T>
Stack<T>::~Stack()
{
	delete[] m_elem;
	m_elem = nullptr;
	m_capacity = 0;
	m_top = -1;
}

template<class T>
void Stack<T>::push(const T & elem)
{
	m_top++;
	// 头指针到了最大容量的时候就扩容,扩展多少取决于数据数量
	if (m_top == m_capacity) {
		int i;
		m_capacity = m_capacity + 10;
		T * temp = new T[m_capacity]; 
		memset(temp, NULL, sizeof(temp));
		for (i = 0; i < m_top; ++i) {
			temp[i] = m_elem[i];
		}
		temp[m_top] = elem;
		m_elem = temp;
		temp = nullptr;
		delete temp;
	}
	else {
		m_elem[m_top] = elem;
	}
}

template<class T>
void Stack<T>::pop()
{
	if (-1 != m_top) {
		m_top--;
	}
}

int main() {
	Stack<int> s(10);
	int n = 20;
	for (int i = 0; i < n; ++i) {
		s.push(i * 2 - 1);
	}
	for (int i = 0; i < n + 1; ++i) {
		s.pop();
	}
	return 0;
}

 


转载:https://blog.csdn.net/CoderMaximum/article/details/101221232
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场