//用java或者C++实现一个堆栈类,并考虑异常
实现思想:用链表实现的一个栈的操作,可以跟据栈的元素个数动态分配内存
尚未在vc环境下调试,算是伪码吧
Struct Node
{
int entry;
int *next;
Node();
Node(int item, Node *add_on = NULL);
};
Node::Node()
{
next = NULL;
}
Node::Node(int item, Node *add_on)
{
entry = item;
next = add_on;
}
Class Stack
{
public:
Stack();
Stack(Node &item);
~Stack();
Error_code push(int item);
Error_code pop();
Error_code top(int &item);
bool empty();
private:
Node *topNode;
};
Stack::Stack()
{
topNode = NULL;
}
Stack::~Stack()
{
while(!empty())
{
pop();
}
}
//简单的单向链表,每次新建一个元素都链到栈顶
Stack::Stack(Node &item)
{
Node *oriangle = item.topNode;
Node *newTop;
Node *newCopy;
if(!oriangle)
{
return;
}
else
{
newCopy = new Node(oriangle->entry);
newTop = newCopy;
oriangle = oriangle->next;
while(oriangle)
{
newCopy->next = new Node(oriangle->entry);
newCopy = newCopy->next;
oriangle = oriangle->next;
}
}
topNode = newTop;
}
//把item 挂到最新的topNode下面
Error_code Stack::push(int item)
{
Node *newNode;
newNode = newNode(item, topNode);
if (!newNode)
{
return overflow;
}
topNode = newNode;
return success;
}
//每次都取栈顶
Error_code Stack::pop()
{
Node *oldNode = topNode;
if (!topNode)
{
return underflow;
}
topNode = topNode->next;
delete oldNode;
return success;
}
//当前的topNode 为空,则为空
bool Stack::empty()
{
return topNode == NULL;
}
Error_code top(int &item)
{
if (!topNode)
{
return underflow;
}
item = topNode->entry;
return success;
}
用java或者C++实现一个堆栈类
最新推荐文章于 2020-11-10 14:47:16 发布