2016-11-29 90 views
-1

我創建了一個隊列,使用兩個來自我創建的堆棧類的堆棧。我想知道是否可以讀出隊列中的所有元素,而不會從堆棧中丟失?在兩個堆棧隊列中創建一個toString

問題是:我可以在MyQueue.java中創建一個toString,它將列出隊列的順序。

這裏是我的兩個文件

MyQueue.java

import java.util.NoSuchElementException; 

public class MyQueue<T> { 
    private MyStack<T> stack1; // back of queue 
    private MyStack<T> stack2; // front of queue 

    public MyQueue() { 
     stack1 = new MyStack<T>(); 
     stack2 = new MyStack<T>(); 
    } 


    private void moveStack1ToStack2()throws Exception { 
     while (!stack1.isEmpty()) 
      stack2.push(stack1.pop()); 
    } 

    public boolean isEmpty() { 
     return stack1.isEmpty() && stack2.isEmpty(); 
    } 

    public T peek() throws Exception { 
     if (isEmpty()) throw new NoSuchElementException("Queue underflow"); 
     if (stack2.isEmpty()) moveStack1ToStack2(); 
     T result = stack2.peek(); 
     return result; 
    } 

    // add the item to the queue 
    public void enqueue(T item) throws Exception 
    { 
     stack1.push(item); 
    } 

    public T dequeue() throws Exception { 
     if (isEmpty()) throw new NoSuchElementException("Queue underflow"); 
     if (stack2.isEmpty()) 
     { 
      moveStack1ToStack2(); 
     } 
     return (T)stack2.pop(); 
    } 
    public int size() 
    { 
     return stack1.size() + stack2.size(); 
    } 


} 

MyStack.java

import java.util.ArrayList; 
import java.util.EmptyStackException; 

public class MyStack<T> { 
    private ArrayList<T> al; 

    public MyStack() { 
     al = new ArrayList<T>(); 
    } 

    public void push(T item) { 
     al.add(item); 
    } 

    public T pop() { 
     if (!isEmpty()) 
      return al.remove(size()-1); 
     else 
      throw new EmptyStackException(); 
    } 

    public boolean isEmpty() { 
     return (al.size() == 0); 
    } 

    public T peek() 
    { 
     if (!isEmpty()) 
      return al.get(size()-1); 
     else 
      throw new EmptyStackException(); 
    } 

    public int size() { 
     return al.size(); 
    } 

    public String toString() 
    { 
     return al.toString(); 
    } 
} 

回答

-1

加入

public String toString() 
{ 
    return stack2.toString(); 
} 

到MyQueue.java

012固定