《数据结构与算法》学习笔记21 递归_消除递归

来源:互联网 发布:c语言0xff是什么意思 编辑:程序博客网 时间:2024/05/16 09:03

//在计算1+2+3+...+n时,不使用递归的方法

//相当麻烦又毫无用处,看半天不太懂,心累

//利用栈实现三角数字相加

public class Parames {

    public intn;   //数值

    public int returnAdd;//标志

    

    public Parames(intnum,int ra){

    n=num;

    returnAdd=ra;

    }

}



public class StackX {

   private Parames[] a;

   public intmsize;

   private int top;

   public StackX(intm){

  a=new Parames[m];

  msize=m;

  top=-1;

   }

   

   public void push(Paramesdata){

  a[++top]=data;

   }

   

   public Parames pop(){

  return a[top--];

   }

   

   public Parames peek(){

  return a[top];

   }

}


import java.io.*;

public class StackTriangleApp {

staticint thenumber;

staticint theanswer;

static StackXthestack;

  staticint codepart;

  static Paramestheparame;

    public staticvoid main(String[] args) throws IOException{

    System.out.println("Input a number:");

    thenumber=getint();

    recTriangle();

    System.out.println(theanswer);

    }

    

    public staticvoid recTriangle(){

      thestack=new StackX(100);

      codepart=1; //开始计算

      while(step()==false);              //step()返回true就是计算结果

    }

    

    public static boolean step(){ //判断计算完成与否

    switch(codepart){

    case 1: //开始计算三角数字

    theparame=new Parames(thenumber,6);//6表示当前数据栈最底层的一个

    thestack.push(theparame);

    codepart=2;//读取下一个数值

    break;

    case 2:

    theparame=thestack.peek();

    if(theparame.n==1){//全部列数都放在栈中,要进行求和

    theanswer=1; //初始设为1

    codepart=5; //取栈中数据

    }else{

    codepart=3; //将当前数值放在栈中的操作

    }break;

    case 3://放入n-1的数值

    Parames newparames=new Parames(theparame.n-1,4);//4表示要求和计算

        thestack.push(newparames);

        codepart=2;

        break;

     case 4://求和计算

     theparame=thestack.peek();

     theanswer=theanswer+theparame.n;

     codepart=5;//取下一个数据

     break;

     case 5: //取下一个数据

     theparame=thestack.peek();

             codepart=theparame.returnAdd;

             thestack.pop();  

             break;

     case 6:

     returntrue;

    }

    returnfalse;

    }

    

    public staticint getint() throws IOException{

    InputStreamReader isr=new InputStreamReader(System.in);

    BufferedReader br=new BufferedReader(isr);

    String s=br.readLine();

    return Integer.parseInt(s);

    }

}



0 0
原创粉丝点击