ALGORITHM 1.1 Pushdown(LIFO) stack (resizing array implementation)(P141)

//可调整大小的stack,且带迭代器

java版:

import java.util.Iterator;
import edu.princeton.cs.algs4.*;

public class ResizingArrayStack<Item> implements Iterable<Item>
{
    private Item[] a = (Item[]) new Object[1];
    private int N = 0;
    
    public boolean isEmpty() {return N == 0;}
    public int size() {return N;}
    
    private void resize(int max)
    {
        Item[] temp = (Item[]) new Object[max];
        for(int i = 0; i < N; i++)
            temp[i] = a[i];
        a = temp;
    }
    
    public void push(Item item)
    {
        if(N == a.length)
            resize(2*a.length);
        a[N++] = item;
    }
    
    public Item pop()
    {
        Item item = a[--N];
        a[N] = null;
        if(N > 0 && N == a.length/4)
            resize (a.length/2);
        return item;
    }
    
    public Iterator<Item> iterator()
    {
        return new ReverseArrayIterator();
    }
    
    private class ReverseArrayIterator implements Iterator<Item>
    {
        private int i = N;
        public boolean hasNext() {return i > 0;}
        public Item next() {return a[--i];}
        public void remove() {};
    }
    
}
java版

//书上这个java版仅仅是一个类

c++版:

#include <iostream>
#include <string>
template<class T>
class ResizingArrayStack
{
    private:
        T *a;
        int N = 0;
        int max_N;
        void resize(int max);
    public:
        ResizingArrayStack(int n = 1);
        ~ResizingArrayStack();
        bool isEmpty();
        int size();
        void push(T c);
        T pop();
};

template<class T>
void ResizingArrayStack<T>::resize(int max)
{
    T * p = new T[max];
    for(int i = 0; i < N; i++)
    {
        p[i] = a[i];
    }
    max_N = max;
    delete[] a;
    a = p;
}

template<class T>
ResizingArrayStack<T>::ResizingArrayStack(int n)
{
    N = 0;
    max_N = n;
    a = new T[n];
}

template<class T>
ResizingArrayStack<T>::~ResizingArrayStack()
{
    delete[] a;
}

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

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

template<class T>
void ResizingArrayStack<T>::push(T c)
{
    if(N == max_N)
        resize(2*max_N);
    a[N++] = c;
}

template<class T>
T ResizingArrayStack<T>::pop()
{
    T c = a[--N];
    if(N <= max_N/4)
        resize(max_N/2);
    return c;
}

int main()
{
    using namespace std;
    int s;
    cout << "input the size " << endl;
    cin >> s;
    ResizingArrayStack<string> p(s);
    string str;    
    while(cin >> str)//终止输入(CTRL + d)
    {
        if(str == "-")
        {
            cout << "pop " << p.pop() << endl;    
        }
        else
        {
            p.push(str);
            cout << "push " << str << endl;
        }
    }
    cout << p.size() << " left on stack" << endl;
    return 0;
}
c++版

//此c++版本带测试的主函数,可运行,但是不带迭代器(主要是我忘记了)

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/8973827.html
今日推荐