题目
JAVA40 排队系统
描述
请设计一个排队程序,用户有普通客人和VIP客人之分,VIP客人不排队(即VIP客人在队列头部),目前队列中已有两位客人小明和小军在排队,请将VIP客人小红新增至队列头部。
输入描述:
无
输出描述:
预设代码中已经指定输出
分析:
1.把vip客户调整至队列头。
代码:
import java.util.*;
public class Main {
public static void main(String[] args) {
Guest guest1 = new Guest("小明",false);
Guest guest2 = new Guest("小军",false);
Guest vipGuest = new Guest("小红",true);
Deque<Guest> deque = new ArrayDeque<>();
deque.add(guest1);
deque.add(guest2);
//write your code here......
deque.addFirst(vipGuest);
System.out.println(deque);
}
}
class Guest{
String name;
Boolean vip;
@Override
public String toString() {
return name;
}
public Guest(String name, Boolean vip) {
this.name = name;
this.vip = vip;
}
}
JAVA41 Head and Tail of the Queue(队列的头和尾)
描述
Students are picked from a group of students to give speeches. To be fair, the head and tail of the queue are drawn alternately. Please implement the process of leaving the queue through the program.(学生是从一群学生中挑选出来发表演讲的。公平地说,队列的头和尾是交替绘制的。请通过程序执行离开队列的过程。)
输入描述:
A group of students’ names
输出描述:
Print the names of the students at the head and tail of the queue alternately.(交替打印排在队伍最前面和最后面的学生的名字。)
示例:
输入:Tom Jim Lily Lucy Mary 输出: Tom Mary Jim Lucy Lily
分析:
1.队列的输出和删除。
代码:
import java.util.ArrayDeque;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayDeque deque = new ArrayDeque();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String name = scanner.next();
// 初始化队列中的数据
deque.offerLast(name);
}
while(deque.size()>=2){
//输出并删除队头元素
System.out.println(deque.pollFirst());
//输出并删除队尾元素
System.out.println(deque.pollLast());
}
if(deque.size()==1){
System.out.println(deque.pollFirst());
}
}
}
大佬代码:
import java.util.ArrayDeque;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayDeque deque = new ArrayDeque();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String name = scanner.next();
// 初始化队列中的数据
deque.offerLast(name);
}
//只要队列大小大于2,不断从队头队尾打印学生名字
while(deque.size()>=2){
System.out.println(deque.pollFirst());
System.out.println(deque.pollLast());
}
//如果队列中还有学生,则必定只有一个学生,直接打印其名字
if(deque.size()>0){
System.out.println(deque.pollFirst());
}
}
}