永发信息网

如何用函数实现入栈和出栈

答案:1  悬赏:30  手机版
解决时间 2021-03-18 10:28
  • 提问者网友:火车头
  • 2021-03-18 05:49
如何用函数实现入栈和出栈
最佳答案
  • 五星知识达人网友:舊物识亽
  • 2021-03-18 06:35
#ifndef Node_
#define Node_

template class LinkedStack;
template class LinkedQueue;

template
class Node {
friend LinkedStack;
friend LinkedQueue;
private:
T data;
Node *link;
};

#endif
// file lstack.h
// linked stack

#include "node.h"
#include "xcept.h"

template
class LinkedStack {
public:
LinkedStack() {top = 0;}
~LinkedStack();
bool IsEmpty() const {return top == 0;}
bool IsFull() const;
T Top() const;
LinkedStack& Add(const T& x);
LinkedStack& Delete(T& x);
private:
Node *top; // pointer to top node
};

template
LinkedStack::~LinkedStack()
{// Stack destructor..
Node *next;
while (top) {
next = top->link;
delete top;
top = next;
}
}

template
bool LinkedStack::IsFull() const
{// Is the stack full?
try {Node *p = new Node;
delete p;
return false;}
catch (NoMem) {return true;}
}

template
T LinkedStack::Top() const
{// Return top element.
if (IsEmpty()) throw OutOfBounds();
return top->data;
}

template
LinkedStack& LinkedStack::Add(const T& x)
{// Add x to stack.
Node *p = new Node;
p->data = x;
p->link = top;
top = p;
return *this;
}

template
LinkedStack& LinkedStack::Delete(T& x)
{// Delete top element and put it in x.
if (IsEmpty()) throw OutOfBounds();
x = top->data;
Node *p = top;
top = top->link;
delete p;
return *this;
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯