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

📄 pex8_5.cpp

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

#include "array.h"

const int MaxStackSize = 50;	// default size of an Array object

template <class T>
class Stack
{
    private:
        // private data members. stack array and top
        Array<T> stacklist;
        int top;
    public:
        // constructor
        Stack (void);     // initialize top
        
        // stack modification operations
        void Push (const T& item);
        T Pop (void);
        void ClearStack(void);
        
        // stack access
        T Peek (void) const;
        
        // stack test methods
        int StackEmpty(void) const;
        // int StackFull(void) const;
};

// initialize stack top
template <class T>
Stack<T>::Stack (void): top(-1)
{}

// push item on the the stack
template <class T>
void Stack<T>::Push (const T& item)
{
    // if all elements of stacklist used, add 10 more
    if (top == stacklist.ListSize()-1)
    	stacklist.Resize(stacklist.ListSize() + 10);

    // increment top and copy item to stacklist
    top++;
    stacklist[top] = item;
}

// pop the stack and return the top element
template <class T>
T Stack<T>::Pop (void)
{
    T temp;

    // if stack is empty, terminate the program
    if (top == -1)
    {
        cerr << "Attempt to pop an empty stack!" << endl;
        exit(1);
    }
    
    // record the top element
    temp = stacklist[top];
    
    // decrement top and return former top element
    top--;
    return temp;
}

// return the value at the top of the stack
template <class T>
T Stack<T>::Peek (void) const
{
    // if the stack is empty, terminate the program
    if (top == -1)
    {
        cerr << "Attempt to peek at an empty stack!" << endl;
        exit(1);
    }

	// cast to T* to use built-in C++ indexing
	// operator. otherwise, get a warning that
	// the overloaded Array indexing operator is
	// not const
    return ((T *)stacklist)[top];
}


// test for an empty stack
template <class T>
int Stack<T>::StackEmpty(void) const
{
    // return the logical value top == -1
   return top == -1;
}

// clear stack
template <class T>
void Stack<T>::ClearStack(void) 
{
    // reset top to -1; resize to MaxStackSize
    stacklist.Resize(MaxStackSize);
    top = -1;
}

void main(void)
{
	Stack<int> S;
	int i, item;
	
	// push values 1..100 on the stack
	for (i = 1; i <= 100; i++)
		S.Push(i);
		
	// empty the stack, printing every 10th value that is popped
	i = 0;
	while (!S.StackEmpty())
	{
		i++;
		item = S.Pop();
		if (i % 10 == 0)
			cout << item << "  ";
	}
	cout << endl;
}

/*
<Run>

91  81  71  61  51  41  31  21  11  1
*/
	

⌨️ 快捷键说明

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