栈的概念及实现
Posted 阿龙亡命天涯
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了栈的概念及实现相关的知识,希望对你有一定的参考价值。
栈的唯一特性:
//Stack.h
#ifndef STACK_H
#define STACK_H
#include "Object.h"
namespace DTLib
template < typename T >
class Stack : public Object
public:
virtual void push(const T& e) = 0;
virtual void pop() = 0;
virtual T top() const = 0;
virtual void clear() = 0;
virtual int size() const = 0;
;
#endif // STACK_H
//StaticStack.h
#ifndef STATICSTACK_H
#define STATICSTACK_H
#include "Stack.h"
#include "Exception.h"
namespace DTLib
template < typename T, int N >
class StaticStack : public Stack<T>
protected:
T m_space[N];
int m_top;
int m_size;
public:
StaticStack() // O(1)
m_top = -1;
m_size = 0;
int capacity() const // O(1)
return N;
void push(const T& e) // O(1)
if( m_size < N )
m_space[m_top + 1] = e;
m_top++;
m_size++;
else
THROW_EXCEPTION(InvalidOperationException, "No space in current stack ...");
void pop() // O(1)
if( m_size > 0 )
m_top--;
m_size--;
else
THROW_EXCEPTION(InvalidOperationException, "No element in current stack ...");
T top() const // O(1)
if( m_size > 0 )
return m_space[m_top];
else
THROW_EXCEPTION(InvalidOperationException, "No element in current stack ...");
void clear() // O(1)
m_top = -1;
m_size = 0;
int size() const // O(1)
return m_size;
;
#endif // STATICSTACK_H
测试
抛异常,大小只有5,却加入10个元素
创建时,调用泛指类型的构造函数,效率很低
解决方案:
基于之前写的链表改写而成:
#ifndef LINKSTACK_H
#define LINKSTACK_H
#include "Stack.h"
#include "LinkList.h"
namespace DTLib
template < typename T >
class LinkStack : public Stack<T>
protected:
LinkList<T> m_list;
public:
void push(const T& e) // O(1)
m_list.insert(0, e);
void pop() // O(1)
if( m_list.length() > 0 )
m_list.remove(0);
else
THROW_EXCEPTION(InvalidOperationException, "No element in current stack ...");
T top() const // O(1)
if( m_list.length() > 0 )
return m_list.get(0);
else
THROW_EXCEPTION(InvalidOperationException, "No element in current stack ...");
void clear() // O(n)
m_list.clear();
int size() const // O(1)
return m_list.length();
;
#endif // LINKSTACK_H
输出1
输出0(多了个双引号)
小结:
以上是关于栈的概念及实现的主要内容,如果未能解决你的问题,请参考以下文章