java实现stack和queue

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;
    }
}
posted @ 2021-05-03 14:43  ibrake  阅读(128)  评论(0编辑  收藏  举报