码迷,mamicode.com
首页 > 其他好文 > 详细

ALGORITHM 1.4 Bag (P155)

时间:2018-05-01 15:14:31      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:不可   迭代器   algorithm   bool   please   code   pac   let   temp   

//用链表实现bag

java版:

技术分享图片
import java.util.Iterator;
import edu.princeton.cs.algs4.*;

public class Bag<Item> implements Iterable<Item>
{
    private Node first;
    private class Node
    {
        Item item;
        Node next;
    }
    
    public void add(Item item)
    {
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
    }
    
    public Iterator<Item> iterator()
    {
        return new ListIterator();
    }
    
    private class ListIterator implements Iterator<Item>
    {
        private Node current = first;
        
        public boolean hasNext()
        {
            return current != null;
        }
        
        public void remove()
        {
        }
        
        public Item next()
        {
            Item item = current.item;
            current = current.next;
            return item;
        }
    }
   
}
java版

//此java版就是书上一模一样的,无main,不可执行

c++版:

技术分享图片
#include <iostream>
#include <string>

template<class T>
class Bag
{

    private:
        class Node
        {
            public:
                T item;
                Node * next;
        };
               Node * first;
    public:
        Bag();
        ~Bag();
        void add(T item);
};

template<class T>
Bag<T>::Bag()
{
}

template<class T>
Bag<T>::~Bag()
{
    while(first != nullptr)
    {
        Node * oldfirst = first;
        first = first->next;
        delete oldfirst;
        std::cout << "delete" << std::endl;
    }
}

template<class T>
void Bag<T>::add(T item)
{
    Node * oldfirst = first;
    first = new Node();
    first->item = item;
    first->next = oldfirst;
}

int main()
{
    using namespace std;
    Bag<string> * p = new Bag<string>();
    string str;
    cout << "please input a string:" << endl;
    while(cin >> str)
    {
        p->add(str);
        cout << "add " << str << endl;
        cout << "please input a string:" << endl;
    }
    delete p;
}
c++版

//原本想加下迭代器,但貌似用不上,我就没加了,感觉全忘了(QAQ)

ALGORITHM 1.4 Bag (P155)

标签:不可   迭代器   algorithm   bool   please   code   pac   let   temp   

原文地址:https://www.cnblogs.com/w-j-c/p/8976192.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!