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.
1def factorial(n):
2 if n == 0:
3 return 1
4 else:
5 return n * factorial(n - 1)
6
7
8number = 5
9print("Factorial of", number, "is", factorial(number))
This Python program calculates the factorial of a number using recursion, showcasing the elegance of recursive functions in Python due to its succinct syntax.