例3.4 使用栈判断回文

来源:互联网 发布:广州sd卡数据恢复 编辑:程序博客网 时间:2024/05/20 18:44
//栈类class Stack{    final int MaxSize = 10;    char[] str;// 栈    int top; // 栈顶指针    public Stack()    {        str = new char[MaxSize];        top = -1; // 初始值为-1    }    // 进栈    public void Push(char c)    {        if (top == MaxSize - 1)        {            System.out.println("Error: Out of MaxSize");            return;        }        top++;        str[top] = c;    }    // 出栈    public char Pop()    {        if (top == -1)        {            System.out.println("Error:Empty Stack");            return '0';        }        char c = str[top];        top--;        return c;    }    // 显示栈中元素    public void DispStack()    {        for (int i = top; i > 0; i--)            System.out.print(str[i] + " ");        System.out.println();    }}public class MyStack{    public static void main(String args[])    {        String s = "12321";        System.out.println(IsHuiWen(s));    }    public static boolean IsHuiWen(String s)    {        Stack stack = new Stack();        char c;        for (int i = 0; i < s.length(); i++)            stack.Push(s.charAt(i));        for (int i = 0; i < s.length(); i++)        {            c = stack.Pop();            if (c != s.charAt(i))                return false;        }        return true;    }}

输出:
true

0 0