题解 | #第K小子串#
队列操作
http://www.nowcoder.com/questionTerminal/e542dfa97dd842578875fa592c982dbb
看到没人写JAVA,斗胆放上我的代码。
写的繁琐了点,欢迎提出改进意见。
import java.util.*; public class Main{ static class Queue{ static class Qnode{ Qnode next; Qnode prev; int value; public Qnode(){} public Qnode(int val){ value = val; } } Qnode head; Qnode tail; int size; public Queue(){ head = new Qnode(); tail = new Qnode(); head.next = tail; tail.prev = head; size = 0; } private int size(){ return size; } private int peek(){ return size == 0 ? -1 : head.next.value; } private int pop(){ if(size == 0) return -1; Qnode temp = head.next; head.next = head.next.next; head.next.prev = head; size--; return temp.value; } private void clear(){ head.next = tail; tail.prev = head; size = 0; } private void push(int val){ Qnode newNode = new Qnode(val); newNode.prev = tail.prev; newNode.next = tail; newNode.prev.next = newNode; tail.prev = newNode; size++; } } public static void main(String args[]){ Scanner sc = new Scanner(System.in); int groups = Integer.parseInt(sc.nextLine()); for(int group = 0; group < groups; group++){ Queue myQ = new Queue(); myQ.clear(); int operations = Integer.parseInt(sc.nextLine()); for(int operation = 0; operation < operations; operation++){ String opcode = sc.nextLine(); int length = opcode.length(); //if length >5 then it is an push operation if(length > 5){ String[] input = opcode.split(" "); int num = Integer.parseInt(input[1]); myQ.push(num); } //if it is a clear opearation if(opcode.equals("CLEAR")){ myQ.clear(); } //if it is a TOP operation if(opcode.equals(("TOP"))){ System.out.println(myQ.peek()); } //if it is a POP operation if(opcode.equals(("POP"))){ int pop = myQ.pop(); if(pop == -1) System.out.println(pop); } //if it is a SIZE operation if(opcode.equals(("SIZE"))){ System.out.println(myQ.size()); } } } } }