Description
请实现以下栈类的定义:
enum ErrorCode
{
success,
underflow,
overflow
};
template
struct Node
{
StackEntry data;
Node *next;
};
template
class MyStack
{
public:
MyStack();
/*
判断栈是否为空,若为空则返回true,非空则返回false
*/
bool empty() const;
int size() const;
/*
出栈操作,若正常出栈则返回success,若栈内无元素则返回underflow
*/
ErrorCode pop();
/*
获取栈顶元素,若正常获取到栈顶元素则返回success,若栈内无元素则返回underflow
元素内容保存在引用参数item中
*/
ErrorCode top(StackEntry &item) const;
/*
入栈操作,若正常入栈则返回success,若入栈失败则返回overflow
*/
ErrorCode push(const StackEntry &item);
/*
清空栈
*/
void clear();
private:
Node<StackEntry> *pTop;
};
注意,只需要提交类的声明以及函数实现,不需要提交main函数。
Hint
注意,只需要提交类的声明以及函数实现,不需要提交main函数。
enum ErrorCode
{
success,
underflow,
overflow
};
template < typename StackEntry>
struct Node
{
StackEntry data;
Node *next;
};
template < typename StackEntry>
class MyStack
{
public:
MyStack() : pTop(NULL){}
/*
判断栈是否为空,若为空则返回true,非空则返回false
*/
bool empty() const {return pTop == NULL;}
int size() const
{
int size = 0;
Node<StackEntry> * p = pTop;
while(p)
{
++size;
p = p->next;
}
return size;
}
/*
出栈操作,若正常出栈则返回success,若栈内无元素则返回underflow
*/
ErrorCode pop()
{
if(empty())
{
return underflow;
}
Node<StackEntry> * p = pTop;
pTop = pTop->next;
delete p;
return success;
}
/*
获取栈顶元素,若正常获取到栈顶元素则返回success,若栈内无元素则返回underflow
元素内容保存在引用参数item中
*/
ErrorCode top(StackEntry &item) const
{
if(empty())
{
return underflow;
}
item = pTop->data;
return success;
}
/*
入栈操作,若正常入栈则返回success,若入栈失败则返回overflow
*/
ErrorCode push(const StackEntry &item)
{
Node<StackEntry> * p = new Node<StackEntry>();
if(!p)
{
return overflow;
}
p->data = item;
p->next = pTop;
pTop = p;
return success;
}
/*
清空栈
*/
void clear()
{
Node<StackEntry> * p = pTop;
while(p)
{
Node<StackEntry> * q = p;
p = p->next;
delete q;
}
pTop = NULL;
}
private:
Node<StackEntry> *pTop;
};
。。。。。。。。。。
跟单链表的操作几乎一样,每次都在链表头插入数据,退栈时从链表头删除,
StackEntry这个的定义在哪里?