Java实现栈(顺序栈,链栈)

Posted Wecccccccc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java实现栈(顺序栈,链栈)相关的知识,希望对你有一定的参考价值。

顺序栈:

package SeqStack;

public class Stack {
    private int top;
    private int base[];
    private int stackSize;

    public Stack()
    {
        stackSize = 100;
        base = new int[stackSize];
        top = -1;
    }

    public Stack(int n)
    {
        stackSize = n;
        base = new int[stackSize];
        top = -1;
    }

    public boolean isFull()
    {
        if (top==stackSize-1) return true;
        return false;
    }

    public boolean isEmpty()
    {
        if (top==-1) return true;
        return false;
    }

    public boolean pushStack(int e)
    {
        if (isFull()) return false;
        base[++top] = e;
        return true;

    }

    public boolean popStack()
    {
        if (isEmpty()) return false;
        --top;
        return true;
    }

    public int topStack()
    {
        if (isEmpty())
        {
            System.out.println("The Stack is empty");
            return 0;
        }
        return base[top];
    }

}

测试类:

package SeqStack;

public class TestStack {
    public static void main(String[] args)
    {
        Stack s = new Stack();
        s.pushStack(23);
        s.pushStack(12);
        s.pushStack(45);
        System.out.println(s.topStack());
        s.popStack();
        System.out.println(s.topStack());
        s.popStack();
        s.popStack();
        s.popStack();
    }
}

链栈:

package LinkStack;

public class Stack {

    private class StackNode
    {
        int data;
        StackNode next;

        public StackNode(int e)
        {
            data = e;
            next = null;
        }
    }

    private StackNode top;

    public Stack()
    {
        top = null;
    }

    public boolean isEmpty()
    {
        if (top==null) return true;
        return false;
    }

    public boolean pushStack(int e)
    {
        StackNode s = new StackNode(e);
        s.next = top;
        top = s;
        return true;
    }

    public boolean popStack()
    {
        if (isEmpty()) return false;
        StackNode p = top;
        top = top.next;
        p.next = null;
        return true;
    }

    public int topStack()
    {
        if (isEmpty())
        {
            System.out.println("The stack is empty");
            return 0;
        }

        return top.data;
    }


}

测试类:

package LinkStack;

import LinkStack.Stack;

public class TestStack {
    public static void main(String[] args)
    {
        Stack s = new Stack();
        s.pushStack(23);
        s.pushStack(12);
        s.pushStack(45);
        System.out.println(s.topStack());
        s.popStack();
        System.out.println(s.topStack());
        s.popStack();
        s.popStack();
        s.popStack();
    }
}

以上是关于Java实现栈(顺序栈,链栈)的主要内容,如果未能解决你的问题,请参考以下文章

顺序栈和链栈实现

java数据结构- - - -栈

N日一篇——Java实现栈

Python数据结构系列❤️《栈(顺序栈与链栈)》——❤️知识点讲解+代码实现

数据结构学习笔记——链式存储结构实现栈(链栈)

数据结构学习笔记——链式存储结构实现栈