刷题-牛客算法入门

AB7 队列

描述
请你实现一个队列。

操作
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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值