链式队列

链式队列是单链表的基础上增加的一种做法


/**
 * 链式队列
 *单链表的基础上增加的一种做法 
 *入队使用为尾插法
 * */

class linkstack{//定义一个链式栈的类

    Entry front=null;//指向第一个结点
    Entry rear=null;//指向最后一个结点
    int usesize=0;


    public linkstack(){

    }
    class Entry{
        int data;
        Entry  next;
        public Entry(){//不含参数的构造函数
            this.data=-1;
            this.next=null;
        }
        public Entry(int data){//含参数的构造函数
            this.data=data;
            this.next=null;
        }

    }
    public boolean isempty(){
        if(this.usesize==0){//当有效数字为0时,说明队列为空
            return true;
        }
        return false;
    }

    //入队,使用尾插法

    public void inserttail(int val){
        Entry entry=new Entry(val);

        if(isempty()){//如果原来没有结点

        this.rear=entry;//rear指向entry
        this.front=this.rear;//头指针也指向entry
        this.usesize++;
        }
        else{
            this.rear.next=entry;//让rear的next域指向entry
            this.rear=entry;//然后rear指向entry,因为rear始终指向最后一个结点
            this.usesize++;
        }

    }
    //出队
    public void pop(){
        if(isempty()){//先判断是否为空
            return ;
        }
    Entry cur=this.front;//因为队列是先进先出,并且我们使用了尾插法,直接删除第一个结点就行
    this.front=cur.next;
    this.usesize--;



    }
    //得到队首元素
    public int gettop(){
        if(isempty()){
            return -1 ;
        }
        return this.front.data;//直接返回front指向的元素就行

    }
    //打印队列
    public void show(){
        if(isempty()){
            return ;
        }
        Entry cur=this.front;
        while(cur!=null){
            System.out.println(cur.data);
            cur=cur.next;
        }
    }
    }


public class test2 {

    public static void main(String[] args) {
        linkstack t1=new linkstack();

        for(int i=0;i<5;i++){
            t1.inserttail(i);
        }
        System.out.println("队头元素为"+t1.gettop());

        t1.show();
        t1.pop();
        System.out.println("===出队后===");
        t1.show();
        System.out.println("队头元素为"+t1.gettop());

        // TODO Auto-generated method stub

    }

}

运行结果:

队头元素为0
0
1
2
3
4
===出队后===
1
2
3
4
队头元素为1

猜你喜欢

转载自blog.csdn.net/qq_37232304/article/details/80279684