簡體   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