数据结构与算法系列—栈

栈的内存示意图

栈的特点

先进后出,后进先先出。

顺序栈代码实现

package com.datastructure.stack;

/**
 * 基于数组实现的顺序栈
 *
 * @Auther: dlm
 * @Date: 2020/4/7 12:33
 * @Description:
 */
public class ArrayStack<T> {

    private static final int DEFAULT_CAPACITY = 1 << 3;  //栈默认大小

    private int capacity;  //栈的大小

    private T[] data;   //存储元素

    private int count;  //栈中元素的个数

    public ArrayStack(int capacity){
        this.capacity = capacity;
        this.data = (T[])new Object[capacity];
        this.count = 0;
    }

    public ArrayStack(){
        this(DEFAULT_CAPACITY);
    }

    //入栈
    public boolean push(T value){
        //栈满
        if(count == capacity)
            return false;

        data[count] = value;
        count++;
        return true;
    }

    // 出栈
    public T pop(){
        //栈空
        if(count == 0)
            return null;

        T obj = data[count-1];
        --count;
        return obj;
    }

}

链栈代码实现

package com.datastructure.stack;

/**
 * 基于链表实现的顺序栈
 * @Auther: dlm
 * @Date: 2020/4/7 12:48
 * @Description:
 */
public class LinkedListStack<T> {

    private Node top = null;   //栈顶指针

    //入栈
    public boolean push(T value){
        Node newNode = null;
        if(top == null)
            newNode = new Node(value,null);

        newNode.next = top;
        top = newNode;
        return true;
    }

    //出栈
    public T pop(){
        if(top == null)
            return null;
        T obj = (T)top.data;
        top = top.next;
        return obj;
    }

    public class Node<T>{

        private T data;

        private Node next;

        public Node(T data,Node next){
            this.data = data;
            this.next = next;
        }
    }
}
欢迎关注个人公众号,可直接扫描以下二维码或微信搜索“阿毛聊技术”。

posted @ 2020-04-07 13:03  limaodeng  阅读(149)  评论(0)    收藏  举报