链表实现队列【大厂算法面试题】

23 篇文章 0 订阅
20 篇文章 0 订阅

题目描述

使用链表实现一个队列简单的基本功能。

实现思路

1、首先自己定义一个链表节点类Node,再定义一个队列类LinkedQueue。
2、offer方法:我们首先判断头节点是否为空,如果为空,就先new一个head节点,接着把值放入head节点,在把tail节点指向head节点,否则,先new一个node节点,把node节点接入tail节点的下个节点,再把tail节点指向tail的下一个节点,让head节点始终保持指向头部节点,tail节点始终指向最后一个节点。
3、poll方法:如果head不为空说明栈中有值,把head节点的value拿出来,在把head节点往下走一步,原来的头节点回因为没有引用而被回收。
4、peek方法:返回head节点的值就行了。
其他的方法就很简单不用细说了。

代码实现

package queue;



/**
 * @author xing xing
 */
public class LinkedQueue {
    private Node head;
    private Node tail;
    private int size = 0;

    public void offer(int value) {
        if (head == null) {
            head = new Node();
            tail = head;
            head.value = value;

        }else {
            Node node = new Node(value);
            tail.next = node;
            tail = tail.next;
        }
        size++;
    }

    public int poll() {
        if (head != null) {
            int value = head.value;
            head = head.next;
            return value;
        }else {
            return -1;
        }
    }

    public int peek() {
        if (head != null) {
            return head.value;
        }else {
            return -1;
        }
    }

    public int size() {
        return size;
    }

    public  boolean isEmpty() {
        return head == null;
    }

    public static void main(String[] args) {
        LinkedQueue linkedQueue = new LinkedQueue();
        linkedQueue.offer(1);
        linkedQueue.offer(2);
        linkedQueue.offer(3);

        System.out.println(linkedQueue.poll());
        System.out.println(linkedQueue.peek());
        System.out.println(linkedQueue.poll());
        System.out.println(linkedQueue.peek());
        System.out.println(linkedQueue.poll());
        System.out.println(linkedQueue.peek());



    }
}

class Node {
    int value;
    Node next;

    public Node(int value) {
        this.value = value;
    }

    public Node(){

    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值