⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pex5_5.h

📁 数据结构C++代码,经典代码,受益多多,希望大家多多支持
💻 H
字号:
#include <iostream.h>
#include <stdlib.h>

const int MaxDualStackSize = 100;

class DualStack
{
	private:
		int top1, top2;
		DataType stackStorage[MaxDualStackSize];		
	public:
		DualStack(void);
		// push elt on stack n
		void Push(DataType elt, int n);
		// pop from stack n
		DataType Pop(int n);
		// peek at stack n
		DataType Peek(int n);
		// is stack n empty?
		int StackEmpty(int n);
		// is stack n full?
		int StackFull(int /*n*/);
		// clear stack n
		void ClearStack(int n);
};

// initialize stack top
DualStack::DualStack (void) : top1(-1), top2(MaxDualStackSize)
{}

// push item on the the stack
void DualStack::Push (DataType elt, int n)
{
    // if stackStorage is full, terminate the program
    if (top1 == top2-1)
    {
        cerr << "Stack " << n << " overflow!" << endl;
        exit(1);
    }
    
    // advance the top and copy item to stackStorage
    if (n == 1)
    {
    	top1++;
    	stackStorage[top1] = elt;
    }
    else
    {
    	top2--;
    	stackStorage[top2] = elt;
    }
}

// pop the stack and return the top element
DataType DualStack::Pop (int n)
{
    DataType temp;

    // if stack is empty, terminate the program
    if ((n == 1 && top1 == -1)  || (n == 2 && top2 == MaxDualStackSize))
    {
        cerr << "Stack " << n << ": Attempt to pop an empty stack!"
        	 << endl;
        exit(1);
    }
    
    // copy item from stackStorage and adjust top
    if (n == 1)
    {
    	temp = stackStorage[top1];
    	top1--;
    }
    else
    {
    	temp = stackStorage[top2];
    	top2++;
    }
    return temp;
}

// return the value at the top of the stack
DataType DualStack::Peek (int n)
{
    // if stack is empty, terminate the program
    if ((n == 1 && top1 == -1)  || (n == 2 && top2 == MaxDualStackSize))
    {
        cerr << "Stack " << n << ": Attempt to pop an empty stack!"
        	 << endl;
        exit(1);
    }
 
    return (n == 1) ? stackStorage[top1] : stackStorage[top2];
}


// test for an empty stack
int DualStack::StackEmpty(int n)
{
   // return the logical value top1 == -1 or
   // top2 == MaxDualStackSize
   return (n == 1) ? top1 == -1 : top2 == MaxDualStackSize;
}

// test for a full stack
int DualStack::StackFull(int /*n*/)
{
   // either stack is full if top1 == top2-1
   return top1 == top2-1;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -