棧和隊列不一樣,棧是後進先出。
實現時用了數組儲存棧,數組大小根據內容自動擴充。
廢話不多說,上代碼(C++)
MyStack.h
#pragma once
template<typename T>
class MyStack
{
private:
int m_tail;
int m_arrSize;
T* m_QueueArray;
public:
MyStack();
~MyStack(void);
bool isEmpty();
bool pushBack(T item);
T pop();//彈出最前一個,並且返回彈出的元素
T top();
int getCount();
};
template<typename T>
int MyStack<T>::getCount()
{
return m_tail+1;
}
template<typename T>
T MyStack<T>::top()
{
return m_QueueArray[m_tail];
}
template<typename T>
MyStack<T>::MyStack()
{
this->m_tail=-1;//尾元素索引地址
this->m_arrSize=2;
this->m_QueueArray=new T[m_arrSize];
}
template<typename T>
MyStack<T>::~MyStack( void )
{
delete[] m_QueueArray;
}
template<typename T>
bool MyStack<T>::pushBack( T item )
{
if ((m_tail+1)==m_arrSize)//數組已滿,需要重新申請空間
{
int newSize=m_arrSize*2;
T* newArr=new T[newSize];
for (int i=0;i<m_arrSize;i++)
{
newArr[i]=m_QueueArray[i];
}
delete[] m_QueueArray;
m_QueueArray=newArr;
m_arrSize=newSize;
}
m_tail++;
m_QueueArray[m_tail]=item;
return true;
}
template<typename T>
bool MyStack<T>::isEmpty()
{
return m_tail==-1;
}
//彈出最後進入棧一個元素
template<typename T>
T MyStack<T>::pop()
{
if(!isEmpty())
{
T t=m_QueueArray[m_tail];
m_tail--;
return t;
}
return T();
}
測試代碼:
#include <iostream>
#include "MyStack.h"
using namespace std;
struct Item
{
int key;
int count;
Item(int _key,int _count)
{
key=_key;
count=_count;
}
Item()
{
key=0;
count=0;
}
};
int main()
{
MyStack<Item> itemStack=MyStack<Item>();
int i=30;
while (i)
{
Item item=Item(i,i);
itemStack.pushBack(item);
i--;
}
itemStack.pop();
itemStack.pop();
itemStack.pushBack(Item(90,90));
itemStack.pushBack(Item(91,91));
Item item;
while(!itemStack.isEmpty())
{
Item item=itemStack.pop();
cout<<item.key<<endl;
}
system("pause");
}