算法导论 顺序双向栈——两个栈共享同一存储空间

本文介绍了如何根据算法导论中的题目,用一个数组实现两个共享存储空间的栈,确保只有当两个栈元素总数达到数组长度时才会溢出。栈的PUSH和POP操作时间复杂度为O(1),并且提供了具体的C++代码实现和运行结果。
摘要由CSDN通过智能技术生成
顺序双向栈——两个栈共享同一存储空间
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值