[英]Create the Queue class and print the element inside from first to last
我目前有一个任务,我需要创建自己的队列类和方法,例如 enqueue()、dequeue(),并从头到尾显示元素。 这是我到目前为止所做的:
节点类:
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;
}
}
这是我的队列类:
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.next = this.rear;
this.rear = node;
}
//get and remove the front node from queue
public String dequeue(){
//check if the queue empty or not
if(this.rear == null){
System.out.println("Queue is empty");
return null;
} else if(this.rear.next == null){ // the queue only have 1 element
this.rear = null;
return this.rear.toString();
} else{ //remove the front node
Node tmp = this.rear;
//traverse to reach the second element
while (tmp.next.next != null) {
tmp = tmp.next;
}
//remove first element
tmp.next = null;
return tmp.next.toString();
}
}
//check if the queue is empty or not
public boolean isEmpty(){
if(this.rear == null){
return true;
} else{
return false;
}
}
//method to display
public void displayQueue(){
if(this.rear == null){
System.out.println("Queue is empty");
} else{
Node tmp = this.rear;
while(tmp != null) {
System.out.print(tmp.data + " ");
tmp =tmp.next;
}
System.out.println();
}
}
}
以及用于测试的主要类:
class Main{
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.enqueue(new Node("1"));
queue.enqueue(new Node("2"));
queue.enqueue(new Node("3"));
queue.displayQueue();
}
}
所以我想要的输出是
1 2 3
但是,我的输出是:
3 2 1
你们能不能看看,我想应该是displayQueue()方法的问题,但是我不知道怎么解决,你们能不能帮帮我。 非常感谢
我相信您的入enqueue
逻辑在很大程度上是正确的,因为您在队列末尾添加新元素并将this.rear
重置为添加的新元素。 但是,您应该使displayQueue
方法递归,以便您可以遵循 FIFO 先进先出原则并从头到尾遍历队列,而不是您现在拥有的遍历队列的方法从结束到开始。 此处推荐递归的原因是,您当前以一种方式构建队列,其中从最后一个节点到第一个节点只有一条单向路由,反之亦然,因此递归方法的基本条件可以是您迭代的节点是null
。 在这一点上,您可以开始打印节点,因为您从队列的开始到结束回溯。 请注意,当您正在迭代的节点是队列的开始时,您正在迭代的节点的next
指针将为null
。 这是带有辅助函数的递归displayQueue
方法的样子,
public void displayQueue(){
if (this.rear == null) {
System.out.println("Queue is empty");
}
else {
displayQueueHelper(this.rear);
}
}
private void displayQueueHelper(Node n) {
if (n == null) {
return;
}
displayQueueHelper(n.next);
System.out.print(n.data + " ");
}
我选择使用递归辅助函数,因为在决定是否遍历队列之前,您仍然应该使用 main 外部displayQueue
函数来检查队列是否为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.