2015-07-26 18:16:21
/**
* The application does an instance of the stack and recursive methods:
* 1, stack operation: Advanced after out,
* 2, Recursive method: direct or call their own method;
* @author LHM
*email:[email protected]
*/
Public class teststack{
//attribute declaration
private string[] item;
//top = 0 o'clock, the stack is empty;
private int top=0;
/**
* Non-parametric construction method
* Default declaration array of 4
*/
Public Teststack () {
item = new STRING[4];
}
/**
* Parametric construction method
* Number of @param i arrays
*/
Public teststack (int i) {
item = new String[i];
}
/**
* Add operations to stacks
* @param the string added by S
*/
Public void push (String s) {
item[top]=s;
top++;
}
/**
* Delete operation of the stack
* Stack is deleted from the top of the stack
*/
public void Pop () {
Item[top-1]=null;
top--;
}
/**
* Returns the value of the element in the stack;
* Return value in the order of advanced post-out
*/
Public void GetInfo () {
for (int j=top-1;j>=0;j--) {
System.out.println (Item[j]);
}
}
//Returns the size of the stack;
public int size () {
return top;
}
/**
* Use recursion to solve 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 ();
///add string in sequence;
Ts.push ("1");
Ts.push ("2");
Ts.push ("3");
Ts.push ("4");
System.out.println ("----------");
System.out.println ("String of the print stack:");
ts.getinfo ();
//ts.pop ();
System.out.println ("----------");
System.out.println ("Factorial of output 3 is:");
System.out.println (TS. Recursion1 (3));
System.out.println ("Factorial of output 5 is:");
System.out.println (TS. Recursion2 (5));
}
}
Program results:
----------
The string that prints the stack:
4
3
2
1
----------
The factorial of the output 3 is:
6
The factorial of the output 5 is:
120
Input: 1,2,3,4, results come out: 4,3,2,1
The factorial of n is calculated by Recursive Method!!
Java Basics (2)--stack and recursive operations