数据结构与算法之栈

丶灬走出姿态 提交于 2019-12-17 03:01:21

 首先:栈是一个特殊的线性表,只允许在一端进行插入(压栈)和删除元素(进栈),这一端称为栈顶。

栈的实现可以用数组实现,称为顺序栈。时间复杂度为O(1)

也可以用链表实现称为链式栈。尾插入栈:O(n),出栈:O(n)
                                                  头插入栈:O(1),从头出栈O(1)

数组实现栈代码如下(运用了泛型):

package stack.com;

public class MyStack<T> {
    public T elem[];
    int top; //top是当前能放元素位置的下标

    public MyStack() {
        this.elem = (T[]) new Object[10];
        this.top = 0;
    }

    //判断是否未满
    private boolean isEmpty() {
        return top == elem.length;
    }

    //入栈
    public void push(T val) {
        if (isEmpty()) {
            return;
        }
        elem[top] = val;
        top++;
    }

    //判断是否为空
    private boolean isFull() {
        return top == 0;
    }

    //出栈
    public T pop() {
        if (isEmpty()) {
            return null;
        }
        T tmp = elem[top-1];
        top--;
        return tmp;
    }

    //查看栈顶元素
    public T peek() {
        return elem[top-1];
    }

}

链表实现栈:

package stack.com;

public class MyListStack {
    class Node {
        int data;
        Node next;

        public Node(int data) {
            this.data = data;
        }
    }
    Node head;

    //入栈
    public void push(int val) {
        Node node = new Node(val);
        node.next = this.head;
        this.head = node;
    }

    //判断是否为空
    private boolean isEmpty() {
        return head == null;
    }

    //出栈
    public int pop() {
        if (isEmpty()) {
            return -1;
        }
        int tmp = head.data;
        head = head.next;
        return tmp;
    }

    //查看栈顶元素
    public int peek() {
        if (isEmpty()) {
            return -1;
        }
        return head.data;
    }


}


 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!