Stack的实现

Stack的实现

  栈(Stack)是一种只能在一个位置进行操作的,LIFO(后进先出)的抽象数据类型。栈的基本操作通常是两种:pop(出栈)和push(入栈),出栈即删除栈顶元素并返回其值,入栈即将元素插入栈顶。

功能描述

  • pop()和push();
  • isEmpty(),判断栈当前是否为null;
  • size() 返回当前栈空间大小。

代码实现

  采用链表和数组实现。

链表实现

  如下,采用链表实现一个栈,MyStack保存栈顶节点的引用,每一个节点又包含对下一个节点的引用。

package com.yam.base;

import java.util.NoSuchElementException;

/**
 * 使用链表实现的栈结构
 * @author: Ympery
 * @date: 2017/3/13 16:30.
 */
public class MyStackList<AnyType> {

    /**
     * 栈顶元素
     */
    private Node<AnyType> top;

    /**
     * 栈当前空间大小
     */
    private int theSize;

    public MyStackList() {
        top = new Node<>(null, null);
        theSize = -1;
    }

    /**
     * 返回栈当前空间大小
     * @return
     */
    public int size() { return ++theSize; }

    /**
     * 判断栈是否为空
     * @return
     */
    public boolean isEmpty() {
        return theSize == -1;
    }

    /**
     * 压栈:讲一个元素压入栈顶
     * @param newVal 要压入栈顶的元素
     * @return
     */
    public boolean push(AnyType newVal) {
        pushNode(newVal);
        return true;
    }

    /**
     * 出栈:取出栈顶元素
     * @return
     */
    public AnyType pop() {
        return popNode().data;
    }

    /**
     * 放入栈顶节点
     * @param newVal
     */
    private void pushNode(AnyType newVal) {
        if (-1 == theSize)
            top.data = newVal;
        else {
            Node<AnyType> newNode = new Node<>(newVal, top);
            top = newNode;
        }

        theSize++;
    }

    /**
     * 取出栈顶节点
     * @return
     */
    private Node<AnyType> popNode() {
        if (-1 == theSize)
            throw new NoSuchElementException();
        Node<AnyType> popNode = top;
        top = top.next;
        theSize--;
        return popNode;
    }

    /**
     * 栈中的元素,包含数据和指向下一个元素的指针
     * @param <AnyType>
     */
    private class Node<AnyType> {

        public Node(AnyType d, Node<AnyType> n) {
            data = d;
            next = n;
        }
        private AnyType data;
        private Node<AnyType> next;
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        MyStackList<Character> stack = new MyStackList<>();

        char c = 'a';

        for (int i = 0; i < 15; i++)
            stack.push(c++);

        while (!stack.isEmpty())
            System.out.print(stack.pop() + " ");

        System.out.println("当前元素个数:" + stack.size());
    }
}

数组实现

  数组实现模仿了ArrayList的add方法,避免了对链表的维护。

package com.yam.base;

/**
 * 使用数组实现的栈结构
 * @author: Ympery
 * @date: 2017/3/13 17:48.
 */
public class MyStackArray<AnyType> {

    private final static int DEFAULT_CAPACITY = 1;

    /**
     * 栈空间大小标记,为-1时表示栈空
     */
    private int theSize;
    private AnyType[] theItems;

    public MyStackArray() { clear(); }

    /**
     * 清理/初始化栈
     */
    public void clear() {
        theSize = -1;
        ensureCapacity(DEFAULT_CAPACITY);
    }

    public boolean isEmpty() { return -1 == theSize; }

    public int size() { return theSize + 1; }

    /**
     * 确保栈空间
     */
    public void ensureCapacity(int newCapacity) {
        if (newCapacity < theSize + 1)
            return;
        AnyType[] old =theItems;
        theItems = (AnyType[]) new Object[newCapacity];

        for (int i = 0; i < size(); i++) {
            theItems[i] = old[i];
        }
    }

    /**
     * 压栈
     * @param val
     */
    public void push(AnyType val) {
        if (theItems.length == size())
            ensureCapacity(2 * size());
        theItems[++theSize] = val;
    }

    /**
     * 出栈
     * @return
     */
    public AnyType pop() {
        AnyType top = theItems[theSize--];
        // 防止连续出栈造成内存浪费
        if (theItems.length / 4 > theSize)
            ensureCapacity(theItems.length / 2);
        return top;
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {

        MyStackArray<Character> stack = new MyStackArray<>();

        char c = 'a';

        for (int i = 0; i < 15; i++)
            stack.push(c++);

        while (!stack.isEmpty())
            System.out.print(stack.pop() + " ");

        System.out.println("当前元素个数:" + stack.size());
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
DFS(深度优先搜索)是一种图遍历算法,可以用来解决很多问题,比如查找图中的连通分量、查找图中的路径等。在Java中,我们可以用Stack实现DFS算法。 DFS使用栈(Stack)数据结构来存储待遍历的节点。具体实现步骤如下: 1. 首先,我们需要创建一个Stack对象来存储待遍历的节点。 2. 然后,我们选择一个起始节点作为DFS的起点,将其入栈。 3. 接着,我们进行循环操作,直到栈为空为止。每次循环中,我们从栈中取出一个节点,将其标记为已访问,并遍历其邻居节点。将邻居节点中未访问过的节点入栈。 4. 最后,当栈为空时,表示DFS遍历结束。 这样就可以使用Stack实现DFS算法。下面是一个简单的Java代码示例: ```java import java.util.Stack; public class DFSStack { public void dfs(int[][] graph, int start) { boolean[] visited = new boolean[graph.length]; Stack<Integer> stack = new Stack<>(); stack.push(start); while (!stack.isEmpty()) { int node = stack.pop(); if (!visited[node]) { visited[node] = true; System.out.print(node + " "); for (int i = 0; i < graph.length; i++) { if (graph[node][i] == 1 && !visited[i]) { stack.push(i); } } } } } public static void main(String[] args) { int[][] graph = { {0, 1, 1, 0, 0}, {1, 0, 0, 1, 0}, {1, 0, 0, 1, 1}, {0, 1, 1, 0, 1}, {0, 0, 1, 1, 0} }; DFSStack dfs = new DFSStack(); dfs.dfs(graph, 0); } } ``` 以上就是用Stack实现DFS算法的一个简单例子。通过这种方式,我们可以使用Stack数据结构来实现深度优先搜索算法,解决各种与图相关的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值