Java數據結構與算法_棧

Java數據結構與算法_棧

一、棧簡介

棧(stack)是限制插入和刪除只能在一個位置上進行的表,該位置是表的末端,叫做棧頂(top)。它是後進先出(LIFO)的。對棧的基本操作只有push(進棧)和pop(出棧)兩種,前者相當於插入,後者相當於刪除最後的元素。
在這裏插入圖片描述

二、棧的Java實現

/**
 * @Author: slx
 * @Date: 2019/5/9 18:37
 */
public class ShuStack {
    private int[] array;
    private int maxSize;
    private int top;

    public ShuStack(int maxSize) {
        this.maxSize = maxSize;
        array = new int[maxSize];
        top = -1;
    }

    //壓入元素
    public void push(int value) {
        if (top < maxSize-1) {
            array[++top] = value;
        }
    }

    //彈出棧頂元素
    public int pop() {
        return array[top--];
    }

    //訪問棧頂元素
    public int peek() {
        return array[top];
    }

    //判斷棧是否爲空
    public boolean isEmpty() {
        return (top == -1);
    }

    //判斷棧是否滿了
    public boolean isFull() {
        return (top == maxSize-1);
    }
}

測試代碼:

/**
 * @Author: slx
 * @Date: 2019/5/9 18:48
 */
public class ShuStackTest {
    public static void main(String[] args) {
        ShuStack stack = new ShuStack(4);
        stack.push(10);
        stack.push(20);
        stack.push(30);
        System.out.println(stack.peek());
        while(!stack.isEmpty()) {
            System.out.print(stack.pop() + " " );
        }
    }
}

結果:

30
30 20 10 
Process finished with exit code 0

三、棧的應用:單詞逆序

import java.util.Stack;
/**
 * @Author: slx
 * @Date: 2019/5/9 18:42
 */
public class TestStringReverse {
    public static void main(String[] args) {
        Stack stack = new Stack();
        String str = "shu push";
        char[] chars = str.toCharArray();
        for (char c : chars) {
            stack.push(c);
        }
        for (int i = 0; i < str.length(); i++) {
            System.out.print(stack.peek());
            stack.pop();
        }
    }
}

結果:

hsup uhs
Process finished with exit code 0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章