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 <stdio.h>
2#include <stdlib.h>
3
4// A simple stack structure in C
5struct Stack {
6 int top;
7 unsigned capacity;
8 int* array;
9};
10
11// Function to create a stack
12struct Stack* createStack(unsigned capacity) {
13 struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));
14 stack->capacity = capacity;
15 stack->top = -1;
16 stack->array = (int*) malloc(stack->capacity * sizeof(int));
17 return stack;
18}
19
20// Stack is full when top is equal to the last index
21int isFull(struct Stack* stack) { return stack->top == stack->capacity - 1; }
22
23// Stack is empty when top is -1
24int isEmpty(struct Stack* stack) { return stack->top == -1; }
25
26// Function to add an item to stack
27void push(struct Stack* stack, int item) {
28 if (isFull(stack))
29 return;
30 stack->array[++stack->top] = item;
31}
32
33// Function to remove an item from stack
34int pop(struct Stack* stack) {
35 if (isEmpty(stack))
36 return -1;
37 return stack->array[stack->top--];
38}
39
40int main() {
41 struct Stack* stack = createStack(100);
42 push(stack, 10);
43 push(stack, 20);
44 push(stack, 30);
45 printf("%d popped from stack\n", pop(stack));
46 return 0;
47}
This C program uses a stack data structure to store integers and perform basic stack operations such as push and pop. The stack is implemented using an array with helper functions to manage stack operations.
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.