用node类创建dequeue方法

kx7yvsdv  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(213)

所以我在这里要做的是,我需要用node class创建自己的队列类。我对myqueue类的dequeue方法有问题。此方法的目的是返回并删除队列的前元素。我知道我在方法中返回了一个错误的值,也就是我返回了后面的值。你们有什么办法让我把前面的元素还给你们吗?任何想法,也可以改善我的代码是感激的。谢谢。这是我的node类代码:

class Node{
    //attributes
    public String data;
    public Node next;

    //basic constructor
    Node(){

    }

    Node(String data){
        this.data = data;
        this.next = null;
    }

    //accessors
    public String getData(){
        return this.data;
    }
    public Node getNext(){
        return this.next;
    }

    //mutators
    public void setData(String tmpData){
        this.data = tmpData;
    }
    public void setNext(Node tmpNext){
        this.next = tmpNext;
    }

    //method to print the data
    public void printNode(){
        if(this.data ==  null){
            System.out.println("NO DATA");
        } else{
            String tmp = this.data;
            while(tmp != null){
                System.out.println(tmp);
            }
        }
    }
}

这是myqueue类

class MyQueue{
    //attributes
    private Node front, rear;

    MyQueue(){
        this.front = null;
        this.rear = null;
    }

    //method to insert one node at the end of the queue
    public void enqueue(Node node){
        node.setNext(this.rear);
        this.rear = node; 
    }

    //get and remove the front node from queue
    public Node dequeue(){
        Node next = this.rear.getNext();
        //check if the queue empty or not
        if(this.rear == null){
            return null;
        } else if(next == null){ // the queue only have 1 element
            this.rear = null;
            return this.rear;
        } else{ //remove the front node
            Node tmp = this.rear;
            //traverse to reach the second element
            while (tmp.getNext().getNext() != null) {
                tmp = tmp.getNext();                
            }
            //remove first element
            tmp.setNext(null);
            return tmp;
        }
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题