Posted on 2006-06-08 20:21
hays(海納百川) 閱讀(673)
評論(1) 編輯 收藏
?????今天在書上看到了一道關于棧的經典例題:用棧實現“4+2*3-10/5”這個算術表達式。于是在eclipe上我先編寫一個棧,功能上是實現了棧的出棧和入棧;
package com.vitam.consloe;
import java.lang.*;
import java.math.*;
import java.util.*;
import java.util.Vector;
public class MyStack {
?private int top;//棧頂top;
?private int length;
?private char[] stack;//用來存儲;
?public MyStack()
?{
??top=0;//指向棧底;
?}
?public MyStack(int n)
?{
??this();
??this.length=n;
??stack= new char[n];
??for(int i =0;i<n;i++)
??{
???stack[i]='#';
??}
?}
?public void setTop(int n)
?{
??this.top=n;
?}
?public int getTop()
?{
??return this.top;
?}
?public void setLength(int n)
?{
??this.length=n;
?}
?public int getLength()
?{
??return this.length;
?}
?public char? outStack()
?{
??char tmp='#';//
??if(top==0)
??{
???System.out.print("棧為空,沒有元素");
??}
??else
??{?
???--top;
???tmp=this.stack[top];
???this.stack[top]='#';
??}
??return tmp;
?}
?public void? pushStack(char n)
?{
?? if(top==stack.length)
?? {
??? System.out.print("棧滿,無法插入元素");
?? }
?? else
?? {
??? this.stack[top]=n;
??? top++;
?? }
?}
}
代碼上有很多不足比如不能插入其他類型的數據(呵呵,其實可以用java自帶的Stack)。可是在編寫過程中獨自思考問題,解決問題到最后調試成功的過程真的很爽!(哎,真郁悶!eclipes怎么調試代碼不太會,害我編了很多測試代碼)。明天看看異常處理,把這個代碼優化下搞個什么StackProgramException 來捕獲棧空棧滿的問題就好了,沒有了if....else.爽。明天就去寫寫,希望能寫出來來。(先去做上面的題目了,棧實現算術表達式)