队列特点
先进先出
队列基本用法
public static void main(String[] args) {
Queue<Integer>queue = new LinkedList<>();
queue.add(1);//放元素
queue.add(2);
queue.add(3);
queue.add(4);
queue.add(5);
queue.add(6);
System.out.println(queue.peek());//获取队首元素
System.out.println(queue.poll());//删除队首元素
System.out.println(queue.peek());
System.out.println(queue.remove());//移除队首元素
System.out.println(queue.peek());
System.out.println(queue.element());//获取队首元素
System.out.println(queue.size());//获取长度
queue.clear();//清空
System.out.println(queue.isEmpty());//判断是否有元素
}
栈实现队列
import java.util.Stack;
public class MyQueue {
Stackstack1 = null;
Stackstack2 = null;
public MyQueue() {
stack1 = new Stack<>();
stack2 =new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
if(stack1.isEmpty()&&stack2.isEmpty()){
stack1.push(x);
}else if(stack2.isEmpty()){
stack1.push(x);
}else if(stack1.isEmpty()){
stack2.push(x);
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(stack1.size()==1){
return stack1.pop();
}else if(!stack1.isEmpty()){
while (stack1.size()>1){
stack2.push(stack1.pop());
}
int i = stack1.pop();
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
return i;
}
return -1;
}
/** Get the front element. */
public int peek() {
if(stack1.size()==1){
return stack1.peek();
}else if(!stack1.isEmpty()){
while (stack1.size()>1){
stack2.push(stack1.pop());
}
int i = stack1.pop();
stack2.push(i);
while (!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return i;
}
return -1;
}
/** Returns whether the queue is empty. */
public boolean empty() {
if(stack1.isEmpty()&&stack2.isEmpty()){
return true;
}
return false;
}
}
队列实现栈
import java.util.LinkedList;
import java.util.Queue;
//队列实现栈
public class MyStack {
Queue<Integer>queue1 =null;
Queue<Integer>queue2 = null;
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
if(queue1.isEmpty()&&queue2.isEmpty()){
queue1.offer(x);
}else if(queue2.isEmpty()){
queue1.offer(x);
}else if(queue1.isEmpty()){
queue2.offer(x);
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
if(!queue1.isEmpty()){
while (queue1.size()>1){
queue2.offer(queue1.poll());
}
return queue1.poll();
}else if(!queue2.isEmpty()){
while (queue2.size()>1){
queue1.offer(queue2.poll());
}
return queue2.poll();
}
return -1;
}
/** Get the top element. */
public int top() {
if(!queue1.isEmpty()){
while (queue1.size()>1){
queue2.offer(queue1.poll());
}
int i =queue1.peek();
queue2.offer(queue1.poll());
return i;
}else if(!queue2.isEmpty()){
while (queue2.size()>1){
queue1.offer(queue2.poll());
}
int i = queue2.peek();
queue1.offer(queue2.poll());
return i;
}
return -1;
}
/** Returns whether the stack is empty. */
public boolean empty() {
if(queue1.isEmpty()&&queue2.isEmpty()){
return true;
}
return false;
}
}