算法4:下压栈C++实现

待解决的问题:

1.未实现迭代器

2.头文件和源文件内容只能放在一个文件里面编译,否则会出现"LNK2019 无法解析的外部符号 ... ..."。

代码:

#include <vector>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

template <class Item>
class ResizingArrayStack
{
private:
    vector<Item> a;
    int N;
    void resize(int max);
public:
    ResizingArrayStack(int cap);
    ~ResizingArrayStack();
    bool isEmpty();
    int size();
    void push(Item item);
    Item pop();
    //Item next();
    void test();
};

template <class Item>
ResizingArrayStack<Item>::ResizingArrayStack(int cap) {
    a.resize(cap);
    N = 0;
};

template <class Item>
ResizingArrayStack<Item>::~ResizingArrayStack() {};

template <class Item>
bool ResizingArrayStack<Item>::isEmpty() { return N == 0; }

template <class Item>
int ResizingArrayStack<Item>::size() { return N; }

template <class Item>
void ResizingArrayStack<Item>::resize(int max) {
    vector<Item> temp(max);
    for (int i = 0; i < N; i++) {
        temp[i] = a[i];
    }
    a = temp;
    temp.clear();
}

template <class Item>
void ResizingArrayStack<Item>::push(Item item) {
    if (N == a.size()) resize(2 * a.size());
    a[N++] = item;
}

template <class Item>
Item ResizingArrayStack<Item>::pop() {
    Item item = a[--N];
    if (N > 0 && N == a.size() / 4) resize(a.size() / 2);
    return item;
}

template <class Item>
void ResizingArrayStack<Item>::test() {
    ResizingArrayStack<string> s(1);

    string file;
    ifstream tobe;

    cout << "输入文件名:";
    cin >> file;
    tobe.open(file, ios::in);

    while (!tobe.eof())
    {
        string item;
        tobe >> item;
        if (!item._Equal("-"))
            s.push(item);
        else if (!s.isEmpty()) cout << s.pop() << " ";
    }
    cout << "(" << s.size() << " left on stack)";
}

 

posted @ 2021-07-28 10:48  Hao_ran  阅读(44)  评论(0编辑  收藏  举报