C++模板實現棧
阿新 • • 發佈:2019-01-09
儘管C++的STL庫裡面有Stack類,但是本著學習的目的,在參考他人成果的基礎上,我決定自己實現一次。這個實現採用的是”連結串列+動態記憶體+模板”的方式實現。眾所周知,棧是一種後進先出的資料結構,即先入棧的元素最後出棧,最後入棧的元素最先出棧。棧常常使用在計算機的變數儲存中。
首先定義元素節點的資料結構:
template<typename T>
struct stackNode
{
T data;//儲存的具體元素
stackNode* next;//指向下一個節點的指標
};
然後需要定義一個MyStack類:
template<typename T>
class MyStack
{
private:
unsigned int count;//計數目前stack中儲存的元素個數
unsigned int maxSize;//stack中最大儲存的元素個數
stackNode<T>* top;//stack頭節點的指標
public:
MyStack();//預設建構函式,建立最多容納10個元素的stack
MyStack(unsigned int ms);//自定義容納個數
~MyStack();//解構函式
int push(T data);//壓棧
int pop(void);//出棧
T getTop(void);//獲取棧頂元素
bool isempty(void);//檢查是否為空
bool isfull(void);//經檢查是否已滿
};
template<typename T>
MyStack<T>::MyStack()
{
count = 0;
maxSize = 10;
top = NULL;
}
template<typename T>
MyStack<T>::MyStack(unsigned int ms)
{
count = 0;
maxSize = ms;
top = NULL;
}
template <typename T>
MyStack<T>::~MyStack()
{
stackNode<T>* p = new stackNode<T>;
for (unsigned int i = count; i >0; i--)
{
p = top;
top = p->next;
delete p;
}
}
template<typename T>
int MyStack<T>::push(T data)
{
count++;
if (isfull())
{
cout << "Error: This Stack is full" << endl;
cout << "File Path =" << __FILE__ << endl;
cout << "Function Name =" << __FUNCTION__ << endl;
cout << "Line =" << __LINE__ << endl;
return 1;
}
stackNode<T>* node = new stackNode<T>;
node->data = data;
node->next = top;
top = node;
return 0;
}
template<typename T>
int MyStack<T>::pop(void)
{
if (isempty())
{
cout << "Error: Stack is empty" << endl;
cout << "File Path =" << __FILE__ << endl;
cout << "Function Name =" << __FUNCTION__ << endl;
cout << "Line =" << __LINE__ << endl;
return 1;
}
stackNode<T>* p = top;
top = top->next;
delete p;
count--;
return 0;
}
template<typename T>
T MyStack<T>::getTop(void)
{
return top->data;
}
template<typename T>
bool MyStack<T>::isempty(void)
{
return count == 0 ? true : false;
}
template<typename T>
bool MyStack<T>::isfull(void)
{
return count > maxSize ? true : false;
}
程式碼不多,測試一下吧
#include<iostream>
#include"myStack.h"
using namespace std;
struct customer
{
char fullname[40];
double payment;
};
int main()
{
MyStack<customer> cus;
customer c[] = { { "Tom", 1000 }, { "Jane", 200.9 }, { "John", 399.22 }, {"Mark",88.99} };
customer temp;
for (int i = 0; i < 4; i++)
{
cus.push(c[i]);
}
double total_payment=0;
for (int i = 0; i < 4; i++)
{
temp = cus.getTop();
cout << "Name" << temp.fullname << endl;
cout << "payment=" << temp.payment << endl;
total_payment += temp.payment;
cout << "total payment=" << total_payment << endl;
cus.pop();
cout << endl;
}
system("pause");
return 0;
}
執行良好。。。。