#ifndef _STACK_H_
#define _STACK_H_
//数组实现
namespace stack_in_array
{
template <typename T>
class Stack
{
private:
enum { MAX = 100 };
T elements[MAX];
int top;
public:
void MakeNull();
bool Empty()const;
bool Full()const;
T Top()const;
void Pop();
void Push(T x);
};
template<typename T>
void Stack<T>::Push(T x)
{
if (Full())
cout << "FULL!\n";
else
{
top++;
elements[top] = x;
}
}
template<typename T>
void Stack<T>::Pop()
{
if (Empty())
cout << "EMPTY!\n";
else
top--;
}
template<typename T>
bool Stack<T>::Full()const
{
return top == MAX - 1;
}
template<typename T>
T Stack<T>::Top()const
{
if (Empty())
cout << "EMPTY!\n";
else
return elements[top];
return NULL;
}
template<typename T>
bool Stack<T>::Empty()const
{
if (top < 0)
return true;
else
return false;
}
template<typename T>
void Stack<T>::MakeNull()
{
top = -1;
}
}
//链表实现
namespace stack_in_linklist
{
template<typename T>
class Stack
{
private:
struct Node
{
T data;
struct Node *next;
};
Node *head;
public:
void MakeNull();
bool Empty()const;
void Push(T x);
void Pop();
T Top()const;
};
template<typename T>
T Stack<T>::Top()const
{
if (!Empty())
return head->next->data;
else
cout << "EMPTY!\n";
return NULL;
}
template<typename T>
void Stack<T>::Pop()
{
Node *p;
if (!Empty())
{
p = head->next;
head->next = p->next;
delete p;
}
else
cout << "EMPTY!\n";
}
template<typename T>
void Stack<T>::Push(T x)
{
Node *p = new Node;
p->data = x;
p->next = head->next;
head->next = p;
}
template<typename T>
bool Stack<T>::Empty()const
{
return head->next == NULL;
}
template<typename T>
void Stack<T>::MakeNull()
{
head = new Node;
s->next = NULL;
}
}
#endif
Stack--C++模板类
最新推荐文章于 2017-10-29 09:00:24 发布