描述
请你实现一个队列。
操作:
push x:将x加入队尾,保证x为int型整数。
pop:输出队首,并让队首出队
front:输出队首:队首不出队
输入描述:
第一行为一个正整数n ,代表操作次数。(1≤n≤100000)
接下来的n,每行为一个字符串,代表一个操作。保证操作是题目描述中三种中的一种。
输出描述:
如果操作为push,则不输出任何东西。
如果为另外两种,若队列为空,则输出 "error“
否则按对应操作输出。
我的实现:(通过链表实现先进先出队列)
与之前实现下压栈的思路差不多:不同的是,需要定义两个结点first、last,分别指向队首和队尾。当进行push操作时,即在last结点后新加一个结点,此时需要判断原先队列是否为空,如果为空,则将新的last值赋给first;当进行pop操作时,即让原先的first结点出队,此时如果原先队列只有一个元素,出队后需要将last置为null。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
MyQueue myQueue = new MyQueue();
while(scanner.hasNextLine()) {
String operation = scanner.nextLine();
String[] result = operation.split(" ");
if (result[0].equals("push")) {
myQueue.push(Integer.parseInt(result[1]));
} else if (result[0].equals("pop")) {
myQueue.pop();
} else if (result[0].equals("front")) {
myQueue.front();
}
}
scanner.close();
}
}
class MyQueue {
private Node first;
private Node last;
private int n = 0;
private class Node {
int item;
Node next;
}
public void push(int x) {
Node oldLast = last;
last = new Node();
last.item = x;
n++;
if (oldLast == null) {
first = last;
return;
}
oldLast.next = last;
}
public void pop() {
if (first == null) {
System.out.println("error");
return;
}
int item = first.item;
Node next = first.next;
if (next == null) {
last = null;
}
first = next;
n--;
System.out.println(item);
}
public void front() {
if (first == null) {
System.out.println("error");
return;
}
System.out.println(first.item);
}
}



