『牛客|每日一题』模板队列
👨🎓作者简介:一位喜欢写作,计科专业大二菜鸟
🏡个人主页:starry陆离🕒首发日期:2022年8月17日星期三
1.每日一题
原题链接:戳我戳我
2.测试案例
6 push 1 pop front push 2 push 3 pop
1 error 2
3.Queue类实现
用Java自带的队列实现,代码如下,只需要做输入获取的处理与三种操作的判断即可,剩下的事情就是调用对应的类方法
Modifier_and_Type | Method and Description |
---|---|
boolean | add(E e) 将指定的元素插入到此队列中,如果可以立即执行此操作,而不会违反容量限制, true 在成功后返回 IllegalStateException 如果当前没有可用空间,则抛出IllegalStateException。 |
E | element() 检索,但不删除,这个队列的头。 |
boolean | offer(E e) 如果在不违反容量限制的情况下立即执行,则将指定的元素插入到此队列中。 |
E | peek() 检索但不删除此队列的头,如果此队列为空,则返回 null 。 |
E | poll() 检索并删除此队列的头,如果此队列为空,则返回 null 。 |
E | remove() 检索并删除此队列的头。 |
import java.util.*; public class Main{ public static void main(String args[]){ Queue<Integer> q=new LinkedList<Integer>(); Scanner in=new Scanner(System.in); int n=in.nextInt(); in.nextLine(); int num; String[] strs; while(n--!=0){ strs=in.nextLine().split(" "); //入队 if(strs[0].equals("push")){ q.add(Integer.parseInt(strs[1])); }else if(strs[0].equals("pop")){ //队不空,队首出列 if(!q.isEmpty()){ System.out.println(q.poll()); }else{ System.out.println("error"); } }else if(strs[0].equals("front")){ //队不空,输出队首 if(!q.isEmpty()){ System.out.println(q.peek()); }else{ System.out.println("error"); } } } } }
4.数组实现队列
import java.util.*; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); int n = Integer.parseInt(scan.nextLine()) ; MyQueue q = new MyQueue(n+1); while(scan.hasNextLine()) { String str = scan.nextLine() ; String arr[] = str.split(" ") ; if(arr[0].equals("push")) { q.push(Integer.parseInt(arr[1])) ; } else if(arr[0].equals("pop")) { q.pop() ; } else { q.front() ; } } } } class MyQueue{ int []arr;//用数组实现队列 int maxSize;//队列的大小 int front;//指示队列首下标 int rear;//指示队尾下标 public MyQueue(int maxSize){ this.maxSize=maxSize; arr=new int[maxSize]; front=-1; rear=-1; } //添加数据 public void push(int val){ //如果队列满了 if(rear==maxSize){ System.out.println("error"); }else{ //添加在队列尾部 rear++; arr[rear]=val; } } //查看头部数据 public void front(){ if(isEmpty()){ System.out.println("error"); }else{ System.out.println(arr[front+1]); } } //取出头部数据 public void pop(){ if(isEmpty()){ System.out.println("error"); }else{ front++; System.out.println(arr[front]); } } //判断队列空 public boolean isEmpty(){ if(rear==front){ return true; } return false; } }
🍁每日推荐:牛客网-面试神器