欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据结构与算法_顺序栈

程序员文章站 2022-06-03 13:33:33
...

MyStack,h:

#ifndef _MYSTACK_H
#define _MYSTACK_H
#include <iostream>
#include "MyUtil.h"
using namespace std;

template<class 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<class T>
MyStack<T>::MyStack(int stackCapacity) : capacity(stackCapacity) 
{
	if(capacity < 1)
		throw "stack capacity musr be > 0!";
	stack = new T[capacity];
	top = -1;	
}

template<class T>
inline bool MyStack<T>::IsEmpty() const
{
	return (top == -1);	//判断句,top=-1返回1, 否则返回-1 
}

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

template<class T>
void MyStack<T>::Push(const T& item)
{
	if(top == capacity - 1)
	{
		//增加栈的大小
		ChangeSize1D(stack, capacity, 2*capacity);
		capacity = 2 * capacity;
	}
	stack[++top] = item;
}

template<class T>
void MyStack<T>::Pop()
{
	if(IsEmpty())
		throw "stack is empty, Cannot delete!";
		
	stack[top--].~T();
}
template<class T>
MyStack<T>::~MyStack()
{
	delete[] stack;
}


#endif

MyUtil,h:

#ifndef _MYUTIL_H
#define _MYUTIL_H
#include <iostream>
using namespace std;

template<class T>
//扩大堆栈的容量
void ChangeSize1D(T* &arr, const int oldSize, const int newSize)
{
	if(newSize < 0)
		throw "New long must be >= 0!";
		
	T* temp = new T[newSize];
	int number = min(oldSize, newSize);
	std::copy(arr, arr+number, temp);
	delete[] arr;
	arr = temp;
}


#endif

main.h

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

using namespace std;

class Dog
{
	
};

int main() 
{
	MyStack<Dog> dog;	//泛型编程 
	MyStack<int> st(200);
	st.Push(99);
	st.Push(55);
	st.Push(66);
	st.Push(77);
	st.Push(88);	
	cout << st.Top() << endl;	
	st.Pop();
	cout << st.Top() << endl;
	st.Pop();
	cout << st.Top() << endl;
	cout << "hello World!" << endl;
	return 0;
}

运行结果:
数据结构与算法_顺序栈

相关标签: 数据结构与算法