This approach uses an iterative method to traverse the structure utilizing a stack for efficient element retrieval and management. This reduces the overhead associated with recursion, like function call stack management.
Time Complexity: O(1) for both push and pop operations.
Space Complexity: O(n) where n is the capacity of the stack.
1#include <iostream>
2#include <stack>
3using namespace std;
4
5int main() {
6 stack<int> s;
7 s.push(10);
8 s.push(20);
9 s.push(30);
10
11 cout << s.top() << " popped from stack\n";
12 s.pop();
13
14 return 0;
15}
This C++ code uses the standard library stack to easily manage data push and pop operations with in-built functionality.
This approach utilizes a recursive method to process elements. It is intuitive and straightforward but needs careful consideration of recursive depth and stack limits in various environments.
Time Complexity: O(n) where n is the input number.
Space Complexity: O(n) due to recursive call stack.
1public class RecursiveDemo {
2 public static int factorial(int n) {
3 if (n == 0) return 1;
4 else return(n * factorial(n - 1));
5 }
6
7 public static void main(String[] args) {
8 int number = 5;
9 System.out.println("Factorial of " + number + " is " + factorial(number));
10 }
11}
This Java program computes the factorial of a number using a recursive method, demonstrating the straightforwardness and concise nature of recursion.