hays

          海納百川
          posts - 25, comments - 48, trackbacks - 0, articles - 0
            BlogJava :: 首頁 ::  :: 聯系 :: 聚合  :: 管理
          ?????今天在書上看到了一道關于棧的經典例題:用棧實現“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.爽。明天就去寫寫,希望能寫出來來。(先去做上面的題目了,棧實現算術表達式)

          評論

          # re: 算術表達式用“?!睂崿F?。?)  回復  更多評論   

          2006-06-09 17:28 by phinecos
          public void setTop(int n)
          {
          this.top=n;
          }
          public int getTop()
          {
          return this.top;
          }
          ========================
          這兩個方法對棧頂指針操作?這樣做不大好吧。。
          另外,是不是可以設置一個private int curLen;這樣的類變量來指示棧中的當前元素個數?

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 遵义市| 改则县| 新津县| 和田市| 天全县| 武邑县| 邵阳市| 龙川县| 秦皇岛市| 清水河县| 永胜县| 田林县| 宜君县| 灵台县| 漾濞| 黄大仙区| 拜城县| 田林县| 宁安市| 隆尧县| 玉屏| 郴州市| 承德县| 霍城县| 栖霞市| 务川| 临邑县| 澳门| 密云县| 宁海县| 玉树县| 黄浦区| 耿马| 金湖县| 恩施市| 湛江市| 乌鲁木齐市| 防城港市| 华宁县| 遂宁市| 贵港市|