0
点赞
收藏
分享

微信扫一扫

链表实现队列~

驚鴻飛雪 2022-02-09 阅读 57
class Node{
    public int val;
    public Node next;
    public Node(int val){
        this.val=val;
    }
}
public class Test {
    public Node head;
    public Node last;
    //入队
    public void offer(int val){
        Node node=new Node(val);
        if(head==null){
            head=node;
            last=node;
        }else{
            last.next=node;
            last=last.next;
        }
    }
    //出队
    public int poll(){
        if(isEmpty()){
            throw new RuntimeException("队列为空");
        }
        int val=head.val;
        head=head.next;
        return val;
    }
    public boolean isEmpty(){
        return head==null;
    }
    //获取队头元素
    public int peek(){
        if(isEmpty()){
            throw new RuntimeException("队列为空");
        }
        return head.val;
    }
}
举报

相关推荐

0 条评论