JAVA41. 首尾交替出队
描述
现从一队学生中抽人上台演讲,为公平起见,队头队尾交替抽取,请通过程序实现这个出队的过程。输入描述
一组学生的名字输出描述
交替打印队头队尾学生的名字示例1
输入:
Tom Jim Lily Lucy Mary
输出:
Tom Mary Jim Lucy Lily
Java 解法, 执行用时: 23ms, 内存消耗: 10536KB, 提交时间: 2022-02-08
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); } // write your code here...... boolean flag = true; for (int i = deque.size(); i > 0; i--, flag = !flag) { if (flag) { System.out.println(deque.pollFirst()); } else { System.out.println(deque.pollLast()); } } } }
Java 解法, 执行用时: 25ms, 内存消耗: 10548KB, 提交时间: 2022-02-08
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); } // write your code here...... int l = deque.size(); for(int i=0; i<l; i++){ if(i%2 ==0){ String name =(String) deque.pollFirst(); System.out.println(name); }else{ String name =(String) deque.pollLast(); System.out.println(name); } } } }
Java 解法, 执行用时: 26ms, 内存消耗: 10476KB, 提交时间: 2022-02-09
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); } // write your code here...... while(deque.size()>=2){ System.out.println(deque.pollFirst()); System.out.println(deque.pollLast()); } if(deque.size()<2){ System.out.println(deque.pollFirst()); } } }
Java 解法, 执行用时: 26ms, 内存消耗: 10500KB, 提交时间: 2021-11-24
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); } // write your code here...... while(deque.size()>0){ String first = (String)deque.pollFirst(); if(first==null){ break; } System.out.println(first); String last = (String)deque.pollLast(); if(last==null){ break; } System.out.println(last); } } }
Java 解法, 执行用时: 26ms, 内存消耗: 10524KB, 提交时间: 2021-11-17
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); } // write your code here...... int len = deque.size(); for (int i = 0; i<len; i++){ if(i%2==0){ System.out.println(deque.pollFirst()); }else{ System.out.println(deque.pollLast()); } } } }