JAVA基礎知識(2)--堆棧和遞迴的操作

來源:互聯網
上載者:User

標籤:

2015-07-26 18:16:21
/**
*該應用程式對堆棧和遞迴方法進行執行個體操作:
*1、堆棧操作:先進後出,
*2、遞迴方法:直接或者調用自己的方法;
*@author lhm

*Email:[email protected]

*/
public class TestStack{
//屬性聲明
private String[] item;
//top = 0時,堆棧為空白;
private int top=0;
/**
*無參構造方法
*預設聲明數組4個
*/
public TestStack(){
item = new String[4];
}
/**
*有參構造方法
*@param i 數組個數
*/
public TestStack(int i){
item = new String[i];
}
/**
* 堆棧的添加操作
* @param s 所添加的字串
*/
public void push(String s){
item[top]=s;
top++;
}
/**
* 堆棧的刪除操作
*堆棧從棧頂開始進行刪除
*/
public void pop(){

item[top-1]=null;
top--;
}
/**
* 返回棧中的元素值;
* 傳回值按先進後出的順序
*/
public void getInfo(){
for(int j=top-1;j>=0;j--){
System.out.println(item[j]);
}
}
//返回堆棧的大小;
public int size(){
return top;
}
/**
*使用遞迴求解n!
*@param n
*/
public int Recursion1(int n){
if(n==0)
return 1;
else
return n*Recursion1(n-1);
}
public int Recursion2(int n){
return n==0? 1:n*Recursion2(n-1);
}
public static void main(String[] args){
TestStack ts = new TestStack();
//依次添加字串;
ts.push("1");
ts.push("2");
ts.push("3");
ts.push("4");
System.out.println("----------");
System.out.println("列印堆棧的字串:");
ts.getInfo();
//ts.pop();
System.out.println("----------");
System.out.println("輸出3的階乘是:");
System.out.println(ts.Recursion1(3));
System.out.println("輸出5的階乘是:");
System.out.println(ts.Recursion2(5));
}
}

 

程式結果:

----------
列印堆棧的字串:
4
3
2
1
----------
輸出3的階乘是:
6
輸出5的階乘是:
120

依次輸入:1,2,3,4,結果出來:4,3,2,1

n的階乘通過遞迴的方法進行計算!!

JAVA基礎知識(2)--堆棧和遞迴的操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.