标签:java public ctr enqueue nullptr fifo read out alt
//链表来做queue
java版:
import edu.princeton.cs.algs4.*; public class Queue<Item> { private Node first; private Node last; private int N; private class Node { Item item; Node next; } public boolean isEmpty() {return first == null;} public int size() {return N;} public void enqueue(Item item) { Node oldlast = last; last = new Node(); last.item = item; last.next = null; if(isEmpty()) first = last; else oldlast.next = last; N++; } public Item dequeue() { Item item = first.item; first = first.next; if(isEmpty()) last = null; N--; return item; } //see page 155 for iterator() implementation. public static void main(String[] args) { Queue<String> q = new Queue<String>(); while(!StdIn.isEmpty())//CTRL + d { String item = StdIn.readString(); if(!item.equals("-")) q.enqueue(item); else if(!q.isEmpty()) StdOut.println(q.dequeue() + " "); } StdOut.println(q.size() + " left on queue"); } }
c++版:
#include <iostream> #include <string> template<class T> class Queue { private: class Node { public: T item; Node * next; }; Node * first; Node * last; int N; public: Queue(); ~Queue(); bool isEmpty(); int size(); void enqueue(T item); T dequeue(); }; template<class T> Queue<T>::Queue() : N(0) { std::cout << "create" << std::endl; } template<class T> Queue<T>::~Queue() { while(first != last) { Node * p = first; first = first->next; delete p; std::cout << "delete" << std::endl; } delete first; std::cout << "delete" << std::endl; } template<class T> bool Queue<T>::isEmpty() { return N == 0; } template<class T> int Queue<T>::size() { return N; } template<class T> void Queue<T>::enqueue(T item) { Node * oldlast = last; last = new Node(); last->item = item; last->next = nullptr; if(this->size() == 0) first = last; else oldlast->next = last; N++; } template<class T> T Queue<T>::dequeue() { T item = first->item; Node * oldfirst = first; first = first->next; if(this->isEmpty()) last = nullptr; delete oldfirst; N--; return item; } int main() { using namespace std; Queue<string> * q = new Queue<string>(); cout << "size " << q->size() << endl; string str; while(cin >> str)//CTRL + d { if(str != "-") { cout << "enqueue " << str << endl; q->enqueue(str); } else if(!q->isEmpty()) { cout << "dequeue " << q->dequeue() << endl; } } cout << q->size() << " left on queue" << endl; delete q; }
ALGORITHM1.3 FIFO qeuue (P151)
标签:java public ctr enqueue nullptr fifo read out alt
原文地址:https://www.cnblogs.com/w-j-c/p/8974662.html