C/C++使用模板实现数据栈

来源:互联网 发布:python caffe 命令行 编辑:程序博客网 时间:2024/05/18 01:56
// 栈.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include <iostream>
#define MAXSIZE 100
using namespace std;
/*
   栈的基本运算
   1. 栈的初始化 (initStack)
   2. 判断栈是否为空(isEmpty)
   3.入栈   (push)
   4.出栈 (pop)
   5.读取栈元素 (GetTop)
*/
template <typename T>
class Stack
{
public:
friend ostream& operator<<(ostream& os, Stack<T>&  rhs)
{
for (int i = 0; i < rhs.Count; i++)
{
os << rhs.Top[i] << "  ";
}
os << endl;
return os;
}
Stack();
Stack(unsigned long EmeCount);
~Stack();
bool IsEmpty();
bool Push(T Element);
bool Pop();
T GetTop();
private:


bool  InitStack(unsigned long EmelentCount);
T* Top;
int Count;


};
template <typename T>
bool Stack<T>::InitStack(unsigned long EmelentCount)
{
Top = (T*)malloc(sizeof(T)*EmelentCount);
if (Top == NULL)
return false;
return true;
}
template <typename T>
Stack<T>::Stack()
{
if (!InitStack(MAXSIZE))
cout << "栈初始化失败!" << endl;
Count = 0;
}
template <typename T>
Stack<T>::Stack(unsigned long ElementCount)
{
if (!InitStack(ElementCount))
cout << "栈初始化失败!" << endl;
Count = 0;
}
template <typename T>
bool Stack<T>::Push(T Element)
{
Count++;
for (int i = Count; i > 0; i--)
{
Top[i] = Top[i - 1];
}
Top[0] = Element;
return true;
}
template <typename T>
T Stack<T>::GetTop()
{
return Top[0];
}
template <typename T>
bool Stack<T>::Pop()
{
for (int i = 0; i < Count; i++)
{
Top[i] = Top[i + 1];
}
Count--;
return true;
}
template <typename T>
bool Stack<T>::IsEmpty()
{
if (Count <= 0)
return true;
else
return false;
}
template <typename T>
Stack<T>::~Stack()
{


}




int _tmain(int argc, _TCHAR* argv[])  9
{
Stack<int> binary;
int Num = 0;

cout << "请输入你想要转换的数字" << endl;
cin >> Num;
while (Num)
{
binary.Push(Num % 2);
Num = Num / 2;
}
cout << binary << endl;
system("pause");
return 0;
}

0 0
原创粉丝点击