思路
因为每次最多只需要处理书顶的k本书,所以只需要维护一个双端队列,用head表示书顶是在队头还是队尾,通过改变head的值达到翻转的效果。剩下将多于的书存入另外一个列表中即可
代码
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
Deque<String> books = new LinkedList<>();
ArrayList<String> res = new ArrayList<>();
for (int i = n-1; i>=0;i--) {
books.addLast(sc.next());
}
int head = 0;
for (int i = 0; i < m; i++) {
String operate = sc.next();
if (operate.equals("ROTATE")){
if (head==0){
while (books.size()>k){
res.add(books.pollLast());
}
head=1;
}else {
while (books.size()>k){
res.add(books.pollFirst());
}
head=0;
}
}else {
String name = operate.substring(4,operate.length()-1);
if (head==0){
books.addFirst(name);
}else {
books.addLast(name);
}
}
}
if (head==0){
while (!books.isEmpty()){
System.out.println(books.pollFirst());
}
}else {
while (!books.isEmpty()){
System.out.println(books.pollLast());
}
}
for (int i = res.size()-1; i>=0; i--) {
System.out.println(res.get(i));
}
}
}