数组模拟栈和队列

一、数组模拟栈

 

#include <iostream>
#include<string.h>
#include<string>
#include<stdio.h>
#include<vector>
#include<math.h>
using namespace std;
template<typename T>
class Stack
{
public:
    Stack(size_t x)
    {
        nSize = x;
        a = new T[nSize];
        //cout << "Stack" << endl;
    }
    ~Stack()
    {
        delete[] a;
        //cout << "~Stack" << endl;
    }

    void push(T x)
    {
        a[index++] = x;
    }
    void pop()
    {
        index--;
    }
    T top()
    {
        if(index-1>=0)
            return a[index-1];
    }
    size_t Size()
    {
        return index;
    }
    bool Empty()
    {
        return index > 0 ? 1 : 0;
    }
private:
    size_t nSize;
    int index = 0;
    T* a;
};
int main()
{
    {
        /*Stack<int> p(1000);
        p.push(1);
        p.push(2);
        cout << p.Size() << endl;
        cout << p.top() << endl;
        p.pop();
        cout << p.top() << endl;*/
        Stack<char> p(1000);
        p.push('a');
        p.push('b');
        p.push('c');
        while (p.Empty())
        {
            cout << p.top() << endl;
            p.pop();
        }
    }
    system("pause");
    return 0;
}

 

 

二、数组模拟队列

#include <iostream>
#include<string.h>
#include<string>
#include<stdio.h>
#include<vector>
#include<math.h>
using namespace std;
template<typename T>
class Queue
{
public:
    Queue(size_t x)
    {
        nSize = x;
        a = new T[nSize];
        //cout << "Queue" << endl;
    }
    ~Queue()
    {
        delete[] a;
        //cout << "~Queue" << endl;
    }

    void push(T x)
    {
        a[last++] = x;
    }
    void pop()
    {
        first++;
    }
    T front()
    {
        if(first<last)
            return a[first];
    }
    size_t Size()
    {
        return last-first;
    }
    bool Empty()
    {
        return last-first > 0 ? 1 : 0;
    }
private:
    size_t nSize;
    int first = 0;
    int last = 0;
    T* a;
};
int main()
{
    {
        /*Queue<int> p(1000);
        p.push(1);
        p.push(2);
        cout << p.Size() << endl;
        cout << p.front() << endl;
        p.pop();
        cout << p.top() << endl;*/
        Queue<char> p(1000);
        p.push('a');
        p.push('b');
        p.push('c');
        while (p.Empty())
        {
            cout << p.front() << endl;
            p.pop();
        }
    }
    system("pause");
    return 0;
}

 

参考博客:https://blog.csdn.net/u010452388/article/details/81567689

posted @ 2020-05-07 17:55  知道了呀~  阅读(259)  评论(0编辑  收藏  举报