Java堆栈Stack的实用小例子

    xiaoxiao2021-11-24  47

    public static void main(String[] args) { change(4587788); String str = "()";//测试一段代码所使用的括号是否正确 System.out.println(bracketMatch(str)); } public static void change(int x) { Stack stack = new Stack();//栈的特点是先进后出,后进先出,用于进制之间的转化很方便 十进制转八进制 while (x > 0) { stack.push(x % 8); x /= 8; } while (!stack.isEmpty()) { System.out.print(stack.pop() + ""); } System.out.println(""); } public static boolean bracketMatch(String str) { Stack stack = new Stack(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); switch (c) { case '{': case '[': case '(': stack.push(Integer.valueOf(c)); break; case '}': if (!stack.isEmpty() && ((Integer) stack.pop()).intValue() == '{') break; else return false; case ']': if (!stack.isEmpty() && ((Integer) stack.pop()).intValue() == '[') break; else return false; case ')': if (!stack.isEmpty() && ((Integer) stack.pop()).intValue() == '(') break; else return false; } } if (stack.isEmpty()) return true; else return false; }
    转载请注明原文地址: https://ju.6miu.com/read-678488.html

    最新回复(0)