C++编程辅导:CSCI104 Stack Implementation
  TEZNKK3IfmPf 2024年08月02日 86 0

Implement a templated ​​Stack​​ class. It must implement the following interface (abstract class), which you should inherit from. In other words, create a file IStack.h which contains this definition, and then your own class (which may be called something like ListStack or ArrayStack or other, depending on how you impement it) should inherit publicly from IStack.

template <class T>
class IStack
{
public:
/* returns whether the stack contains any elements */
virtual bool isEmpty() const = 0;

/* adds a value to the top of the stack */
virtual void push(const T& val) = 0;

/* deletes the top value from the stack.
Throws EmptyStackException if stack was empty.
However, you should avoid having this exception thrown,
by checking whether the stack is empty before calling it. */
virtual void pop() = 0;

/* returns the top value on the stack.
Throws EmptyStackException if stack was empty.
However, you should avoid having this exception thrown,
by checking whether the stack is empty before calling it. */
virtual const T& top() const = 0;
};
复制代码

Your implementation can reuse some of your earlier linked list code, or you can build it on top of an array (which you dynamically allocate) - your choice. You must ensure that all functions run in time O(1) (amortized time O(1) if you use an array implementation), and should give an explanation with your code for why your code runs in O(1) time.
Your solution to this problem absolutely cannot use ​​STL​​ container classes (so no stack or vector or deque or list or such provided by STL).

Analysis

Stack,也就是数据结构中的​​栈​​。本题定义了栈的模板和接口,我们只需要实现isEmpty(),push(),pop(),top()这四个函数,以及类的构造函数和析构函数即可。我们可以利用​​linked list​​,即​​线性链表​​来存储数据,这样也能保证functions run in time O(1),即时间复杂度为1。
另外一点需要注意的是,本题不能使用​​STL模板库​​,因此基本的数据结构都需要我们来实现。

Tips

下面简单给出ListStack.h文件的示例代码

template <class T>
class ListStack: public IStack
{
public:
ListStack();
ListStack(int sz = 20);
ListStack(const ListStack<T>& ls);
~ListStack();

void bool isEmpty() const;
void push(const T& val);
void pop();
const T& top() const;
private:
T* listStack;
int size;
}
复制代码
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年08月02日 0

暂无评论

推荐阅读
TEZNKK3IfmPf