Posted on 2006-06-08 20:21
hays(海納百川) 閱讀(667)
評(píng)論(1) 編輯 收藏
?????今天在書(shū)上看到了一道關(guān)于棧的經(jīng)典例題:用棧實(shí)現(xiàn)“4+2*3-10/5”這個(gè)算術(shù)表達(dá)式。于是在eclipe上我先編寫一個(gè)棧,功能上是實(shí)現(xiàn)了棧的出棧和入棧;
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;//用來(lái)存儲(chǔ);
?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("棧為空,沒(méi)有元素");
??}
??else
??{?
???--top;
???tmp=this.stack[top];
???this.stack[top]='#';
??}
??return tmp;
?}
?public void? pushStack(char n)
?{
?? if(top==stack.length)
?? {
??? System.out.print("棧滿,無(wú)法插入元素");
?? }
?? else
?? {
??? this.stack[top]=n;
??? top++;
?? }
?}
}
代碼上有很多不足比如不能插入其他類型的數(shù)據(jù)(呵呵,其實(shí)可以用java自帶的Stack)。可是在編寫過(guò)程中獨(dú)自思考問(wèn)題,解決問(wèn)題到最后調(diào)試成功的過(guò)程真的很爽!(哎,真郁悶!eclipes怎么調(diào)試代碼不太會(huì),害我編了很多測(cè)試代碼)。明天看看異常處理,把這個(gè)代碼優(yōu)化下搞個(gè)什么StackProgramException 來(lái)捕獲棧空棧滿的問(wèn)題就好了,沒(méi)有了if....else.爽。明天就去寫寫,希望能寫出來(lái)來(lái)。(先去做上面的題目了,棧實(shí)現(xiàn)算術(shù)表達(dá)式)