顺序栈

目录

MyStack.h

#ifndef _MYSTACK_H
#define _MYSTACK_H 

#include "MyUtil.h"

template <typename T>
class MyStack
{
public:
	MyStack(int stackCapacity = 10);
	~MyStack();
	bool IsEmpty() const; // 判断是否空
	T& Top() const; 	  // 取栈顶元素
	void Push(const T& item); // 放进元素
	void Pop(); // 删除元素

private:
	T* stack;
	int top;
	int capacity;
	
};

template <typename T>
void MyStack<T>::Pop()
{
	if(IsEmpty()) throw "Stack is empty, cannot delete";
	stack[top--].~T();

}

template <typename T>
inline bool MyStack<T>::IsEmpty() const
{
	return top == -1;
}

template <typename T>
inline T& MyStack<T>::Top() const
{
	if(IsEmpty()) throw "Stack is empty";
	return stack[top];
}

template <typename T>
MyStack<T>::MyStack(int stackCapacity):capacity(stackCapacity)
{
	if (capacity < 1) throw "stack capacity must be > 0";
	stack = new T[capacity];
	top = -1; // 没有数据的时候
	
}

template <typename T>
MyStack<T>::~MyStack()
{
	delete[] stack;
}

template <typename T>
void MyStack<T>::Push(const T& item)
{
	if(top == capacity-1)
	{
		ChangeSize1D(stack, capacity, 2*capacity);
		capacity *= 2;
	}
	stack[++top] = item;
}

#endif

MyUtil.h

#ifndef _MYUTIL_H
#define _MYUTIL_H

#include <iostream>

template <typename T>
void ChangeSize1D(T* &a, const int oldSize, const int newSize);

template <typename T>
void ChangeSize1D(T* &a, const int oldSize, const int newSize)
{
	if(newSize < 0) throw "New length must be >= 0";

	T* temp = new T[newSize];
	int number = std::min(oldSize, newSize);
	std::copy(a, a+number, temp);
	delete[] a;
	a = temp;
}


#endif

main.cpp

/*
* author:起风了_Zoe
* date:2020.04.07
*/

#include <iostream>
#include <string>
#include "MyStack.h"

using namespace std;

class anything
{

};

int main()
{
	MyStack<string> myStringStack;
	MyStack<anything> angStack;
	MyStack<int> st;
	st.Push(20);
	st.Push(22);
	st.Push(24);
	st.Push(26);
	cout << st.Top() << endl;
	st.Pop();
	cout << st.Top() << endl;	
	st.Pop();
	cout << st.Top() << endl;	
	st.Pop();
	cout << st.Top() << endl;	
	cout << "OK!!!" << endl;
	return 0;
}
上一篇:leetcode---用队列实现栈


下一篇:自己实现一个栈结构