Skip to content

Instantly share code, notes, and snippets.

@zhangr4
Created July 11, 2022 14:51
Show Gist options
  • Save zhangr4/99b2b23fd007bb4a15b06d32e64a94d9 to your computer and use it in GitHub Desktop.
Save zhangr4/99b2b23fd007bb4a15b06d32e64a94d9 to your computer and use it in GitHub Desktop.
a trial on using stack implement fibonacci
import java.util.Stack;
class Program {
public static void main(String[] args) {
for(int i = 0; i <= 10; i++) {
System.out.print(fibonacci(i) + " ");
}
System.out.println();
for(int i = 0; i <= 10; i++) {
System.out.print(stackFibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if(n == 0 || n == 1) {
return n;
}
return fibonacci(n-1) + fibonacci(n - 2);
}
public static int stackFibonacci(int n) {
if(n == 0 || n == 1) {
return n;
}
Stack<Integer> stack = new Stack<Integer>();
int i = 2;
stack.push(0);
stack.push(1);
while(i <= n) {
int f1 = stack.pop();
int f0 = stack.peek();
int temp = f0 + f1;
stack.push(f1);
stack.push(temp);
i++;
}
return stack.peek();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment