链式队列

//链式队列   单链表形式上增加的一种  用来实现入队O(1)  出队O(1)
public class TestLinkQueue {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        LinkQueue k=new LinkQueue();
        k.insertTail(111);
        k.insertTail(222);
        k.insertTail(333);
        k.show();
        System.out.println("---");
        k.pop();
        k.show();
        int i=k.getTop();
        System.out.println(i);
    }

}
class LinkQueue{
    class Entry{
        int data;
        Entry next;
    
        public Entry(){
           int data=-1;
           next=null;
        }
        public Entry(int data){
           this.data=data;
           this.next=null;
        }
    }
    private Entry front=null;
    private Entry rear=null;
    private int usedSize=0;
    
    public boolean isEmpty(){
        
        if(usedSize==0){//这里我原来写的front==rear
            return true;
        }
        return false;
    }
    //入队  用尾插法实现
    public void insertTail(int val){
        if(isEmpty()){
            this.rear=new Entry(val);
            this.front=this.rear;
            }else{
                this.rear.next=new Entry(val);
                this.rear=this.rear.next;
            }
        this.usedSize++;
    }
    //出队
    public void pop(){
        if(isEmpty()){
            return;
        }else{
        Entry cur=this.front;
        this.front=cur.next;
        cur.next=null;//回收了  这里我认为是cur=null;
        }
        this.usedSize--;
    }
    //得到队头元素
    public int getTop(){
        if(isEmpty()){
            return -1;
        }
        return this.front.data;
    }
    public void show(){
        Entry cur=this.front;
        while(cur!=null){
            System.out.println(cur.data+" ");
            cur=cur.next;
        }
        System.out.println();
    }
    
}

 

posted on 2018-05-11 14:12  番茄疯了  阅读(152)  评论(0)    收藏  举报