Algs4-1.3.32链表实现Stack和Queue的合体Steque

1.3.32Steque。一个以栈为目标的队列(或称为steque),是一种支持push、pop、和enqueue操作的数据类型。为这种抽象数据类型定义一份API并给出一份基于链表的实现。
import java.util.Iterator;
public class Steque<Item> implements Iterable<Item>
{
    private int N;
    private Node first;
    private Node last;
   
    private class Node
    {
        Item item;
        Node next;
    }
   
    public boolean isEmpty()
    {return N==0;}
   
    public int size()
    {return N;}
   
    public void push(Item item)
    {
        Node oldfirst=first;
        first=new Node();
        first.item=item;
        first.next=oldfirst;
        if(isEmpty()) last=first;
        N++;
    }
   
    public Item pop()
    {
        Item item=first.item;
        first=first.next;
        N--;
        if(isEmpty()) last=null;
        return item;
    }
   
    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;
        N--;
        if(isEmpty()) last=null;
        return item;
   }
   
    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;
        }//end next
      }//end class ListIterator
    public static void main(String[] args)
    {
        Steque<String> q=new Steque<String>();
        while(!StdIn.isEmpty())
        {
            String item=StdIn.readString();
            q.enqueue(item);
         }//end while
        for(String item:q)
        StdOut.println(item+" ");
    }//end main
}//end class

posted @ 2018-10-26 08:35  修电脑的龙生  阅读(342)  评论(0编辑  收藏  举报