栈的基本操作和使用示例(java)

Posted yuwenS.

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了栈的基本操作和使用示例(java)相关的知识,希望对你有一定的参考价值。

栈(stack)又名堆栈,它一种拥有先进后出特点的线性表数据结构。有栈顶和栈底,能插入数据的称为栈顶,另一端不能插入数据的为栈底。向栈中插入新数据称为进栈、入栈或压栈,插入的这个新数据把之前的栈顶元素替代成为新栈顶的元素;从栈里删除一个元素称为出栈或退栈,这个是把栈顶元素删除,将栈顶元素下方的第一个元素成为新栈顶元素。

代码实现

栈一般会有三个操作

  1. push 入栈:向栈中添加数据
  2. pop 出栈:从栈中删除数据
  3. peek 返回栈顶数据

具体实现

public class ArrayStack 
    //栈的大小
    private int maxStack;

    //数组用来模拟栈
    private int[] stack;

    //表示栈顶所在位置,默认没有数据时,使用-1
    private int top = -1;
    public ArrayStack(int maxStack)
        this.maxStack = maxStack;
        stack = new int[maxStack];
    

    //判断是否满栈
    public boolean isFull()
        return this.top == this.maxStack - 1;
    

    //判断是否是空栈
    public boolean isEmpty()
        return this.top == -1;
    

    //压栈
    public void push(int val)
        //是否满栈
        if (isFull())
            throw new RuntimeException("此栈已满");
        
        top++;
        stack[top] = val;
    

    //出栈
    public int pop()
        if (isEmpty())
            throw new RuntimeException("这是个空栈");
        
        int value = stack[top];
        top--;
        return value;
    

    //查看栈中所有元素
    public void list()
        if (isEmpty())
            throw new RuntimeException("这是个空栈");
        
        for (int i = 0; i < stack.length; i++) 
            System.out.println("第"+i+1+"个数: "+stack[i]);
        
    
    
    //获取栈顶数据
    public int peek()
        return this.stack[top];
    
    
	//栈中有多少数据
    public int length()
        return this.top+1;
    

使用示例

用栈来判断一个字符串是否为回文

代码实现依据上面栈的操作来实现

public class Test

    public static void main(String[] args) 
        System.out.println(detecation("helloworld"));
        System.out.println(detecation("abccba"));
    
    
    //判断输入的字符是否为回文
    public static boolean detecation(String val)
    
        // 初始化对象
        ArrayStack arrayStack = new ArrayStack(10);
        
        //获取字符串的长度
        int length = val.length();
        
        //把字符串数据压入栈中
        for (int i = 0; i < length; i++) 
            arrayStack.push(val.charAt(i));
        
        String str = "";
        int length1 = arrayStack.length();
        
        //把数据从栈中读取出来
        for (int i = 0; i < length1; i++) 
            if (!arrayStack.isEmpty())
                str += (char)arrayStack.pop();
            
        
        return val.equals(str);
    

运行结果

总结

  • 栈中的数据是先进后出方式出栈的
  • 栈中添加或删除数据都只能从栈顶操作

以上是关于栈的基本操作和使用示例(java)的主要内容,如果未能解决你的问题,请参考以下文章

java中的基本数据类型存放位置

java中的基本数据类型存放位置

数据结构(Java语言)——Stack简单实现

Java 大话数据结构 线性表之栈

Java中栈的使用

Java堆,栈,堆栈