顺序双向栈——两个栈共享同一存储空间
1. 什么是双向栈?
算法导论原题:
10.1-2
Explain how to implement two stacks in one array A[1..n] in such a way that neither stack overflows unless the total number of elements in both stacks together is n.The PUSH and POP operations should run in O(1) time.
即:用数组 A[1..n] 实现两个栈,只有当它们的数据元素和为n的时候才会上溢。PUSH和POP操作都应该是O(1)。
2. 如何实现双向栈?
- 单向栈可以看作只能从左端push,所以这个双向栈可以看作从左右任意一端push,由原来的一个top指向改为两个top指向,一个从左端开始,一个从右端开始。
- 判断栈满,只需要判断左端的top超过右端的top即为栈满。
3. 栈的实现(C++代码)
//BothwayStack.h
#pragma once
#include <assert.h>
template<typename ElemType>
class BothwayStack
{
public:
enum Direction{E_Left,E_Right};
BothwayStack(unsigned int size);
bool Push(Direction direction, ElemType elem);
bool Pop(Direction direction, ElemType* elem);
bool Empty(Direction direction);
bool Visit(ElemType* elem, unsigned int pos);
private:
unsigned int m_size;
unsigned int m_leftTop;
unsigned int m_rightTop;
ElemType* m_array;
};
template<typename ElemType>
bool BothwayStack<ElemType>::Visit(ElemType* elem, unsigned int pos)
{
if (pos >= m_size || pos < 0)
{
assert(false && "Error: Visit Pos is out range of array!");
return false;
}
*elem = m_array[pos];
return true;
}
template<typename ElemType>
bool BothwayStack<ElemType>::Empty(Direction