标签:不可 迭代器 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版就是书上一模一样的,无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; }
//原本想加下迭代器,但貌似用不上,我就没加了,感觉全忘了(QAQ)
标签:不可 迭代器 algorithm bool please code pac let temp
原文地址:https://www.cnblogs.com/w-j-c/p/8976192.html