首页 > 编程语言 > 详细

java实现stack和queue

时间:2021-05-03 19:16:59      阅读:29      评论:0      收藏:0      [点我收藏+]

1、stack

java语言实现stack。

package kb.algorithm;


public class Stack<Item> {
    private Node first;
    private int N;

    public boolean empty() {
        return first == null;
    }

    public int size() {
        return N;
    }

    public void push(Item item) {
        Node oldFirst = first;
        first = new Node();
        first.item = item;
        first.next = oldFirst;
        N++;
    }

    public Item pop() {
        if (empty()) {
            return null;
        }
        Item item = first.item;
        first = first.next;
        N--;
        return item;
    }

    private class Node {
        Item item;
        Node next;
    }
}

2、queue

java语言实现queue。

package kb.algorithm;

public class Queue<Item> {
    private Node first;
    private Node last;
    private int N;

    public boolean empty() {
        return first == null;
    }

    public int size() {
        return N;
    }

    public void enqueue(Item item) {
        Node oldLast = last;
        last = new Node();
        last.item = item;
        last.next = null;
        if (empty()) {
            first = last;
        } else {
            oldLast.next = last;
        }
        N++;
    }

    public Item dequeue() {
        if (empty()) {
            return null;
        }
        Item item = first.item;
        first = first.next;
        if (empty()) {
            last = null;
        }
        N--;
        return item;
    }

    private class Node {
        Item item;
        Node next;
    }
}

java实现stack和queue

原文:https://www.cnblogs.com/Brake/p/14727453.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!