Steque--以栈为目标的队列--基于链表实现

是一种支持push,pop,enqueue操作的数据类型。push和pop都是对队列同一端的操作,enqueue和push对应,但是操作的是队列的另一端

和栈的思想基本一致,但是多维护一个指向栈底(也就是链表尾部)的指针,方便进行enqueue操作

/**
 * @author 鯉伴MAY
 * @param <Item> 泛型
 */
public class Steque <Item>{
    private class StequeNode {
        Item item;
        StequeNode next;
    }
    private StequeNode first;
    private StequeNode last;
    private int N;
    private boolean isEmpty(){
        return first == null;
    }
    private int size() {
        return N;
    }

    //创建新的节点
    private StequeNode newNode(Item item) {
        StequeNode temp = new StequeNode();
        temp.item = item;
        return  temp;
    }

    //从顶部栈顶/队头插入节点
    public void push(Item item) {
        StequeNode xNode = newNode(item);
        if(isEmpty()) {
            first = xNode;
            last = xNode;
        }else {
            xNode.next = first;
            first = xNode;
        }
        N++;
    }

    //从顶部弹出节点
    public Item pop() {
        if(isEmpty()){
            System.out.println("栈已空");
            return null;
        }
        StequeNode temp = first;
        if(size() == 1) {
            first = null;
            last = null;
        }else {
            first = first.next;
            temp.next = null;
        }
        N--;
        return temp.item;
    }

    //队尾插入节点
    public void enqueue(Item item) {
        StequeNode xNode = newNode(item);
        if(isEmpty()) {
            first = xNode;
            last = xNode;
        }else {
            last.next = xNode;
            last = xNode;
        }
        N++;
    }

    public void printStack() {
        StequeNode temp = first;
        while(temp != null) {
            System.out.println(temp.item);
            temp = temp.next;
        }
    }
}
posted @ 2019-10-14 20:21  dwwzone  阅读(179)  评论(0编辑  收藏  举报