繁体   English   中英

在我下面实现的队列中,学生从最旧到最新显示。我想从最新到最旧显示插入的学生

[英]In the queue I have implemented below the students are displayed from oldest to newest.I want to display inserted students from the newest to oldest

队列的驱动程序代码

import java.util.Scanner;

public class Driver {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("How many Students are there ? ");
    int usercount = sc.nextInt();

    Queue obj = new Queue(usercount);

    boolean flag = true;
    while(flag) {
    System.out.println("Queue Operations");
    System.out.println("====================");
    System.out.println("1.Insert Students Name");
    System.out.println("2.Remove First inserted student");
    System.out.println("3.Display All Students");
    System.out.println("4.Exit");
    System.out.println("========================");

    System.out.println("Enter Your Choice : ");
    String userchice = sc.next();
    if(userchice.equalsIgnoreCase("1")) {
    for(int i=0; i<usercount; i++) {
    System.out.println("Enter Student Name : ");
    String sname = sc.next();
    obj.Enqueue(sname);
    }
    }else if(userchice.equalsIgnoreCase("2")) {
    obj.Dequeue();
    }else if(userchice.equalsIgnoreCase("3")) {
    obj.displayall();
    }else if(userchice.equalsIgnoreCase("4")) {
    System.out.println("End of Program");
    flag = false;
    }
    }

  }

}

队列的代码

public class Queue {
int front;
int rear;
String[] username;
int size;

 public Queue(int usercount) {
 this.size = usercount;
 this.front = 0;
 this.rear = -1;
 this.username = new String[usercount];
 }

 public Boolean isFull() {
 if( this.rear == this.size - 1 ) {
 return true;
 }else {
 return false;
 }
 }

 public Boolean isEmpty() {
 if( (this.rear == -1) || (this.rear < this.front) ) {
 return true;
 }else {
 return false;
 }
 }



 public void Enqueue(String item) {
 if(isFull()) {
 System.out.println("Queue is Full.Cannot Insert");
 }else {
 this.rear++;
 this.username[rear] = item;
 System.out.println("Element " + item + " is inserted.");
 }
 }

 public void Dequeue() {
 if(isEmpty()) {
 System.out.println("Queue is Empty.Cannot Delete");
 }else {
 String topelem = this.username[front];
 this.username[front] = "";
 System.out.println("Top Element " + topelem + " is removed.");

 for(int i=0; i < rear ; i++) {
 this.username[i] = this.username[i+1];
 }

 this.username[rear] = "";
 this.rear--;
 }
 }

 public void displayall() {
 for(int i=0; i < this.size ; i++) {
 System.out.println("Name = " + username[i]);
 }
 }

}

**假设我在 1 中的选择中输入 a,b,c 作为学生。当我输入选择为 3(显示所有学生)时,结果是

  1. 名称 = a 名称 = b 名称 = c

我想要的是结果

  1. 名称 = c 名称 = b 名称 = a

这不是硬件或任务。 这是我自己在练习的东西。我真的不知道如何开始。

**

只需尝试执行反向 for 循环。

for(int i = rear;i>=0;i--) {
    System.out.print(this.username[i]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM