Repository navigation
Expand file tree
/
Copy pathStackCodeRepository.java
More file actions
1431 lines (1202 loc) · 61.4 KB
/
Copy pathStackCodeRepository.java
File metadata and controls
1431 lines (1202 loc) · 61.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.simulator;
import java.util.HashMap;
import java.util.Map;
public class StackCodeRepository {
private final Map<String, CodeExample> codeExamples;
public StackCodeRepository() {
codeExamples = new HashMap<>();
initializeCodeExamples();
}
private void initializeCodeExamples() {
// =============== BASIC STACK OPERATIONS ===============
codeExamples.put("Create Stack", new CodeExample(
"Create Stack",
"Basic Stack class structure with array/list implementation",
"O(1)",
"""
// Stack implementation using ArrayList
import java.util.ArrayList;
import java.util.EmptyStackException;
public class Stack<T> {
private ArrayList<T> stack;
private int maxSize;
// Constructor
public Stack() {
this(100); // Default max size
}
public Stack(int maxSize) {
this.maxSize = maxSize;
this.stack = new ArrayList<>();
}
// Check if stack is empty
public boolean isEmpty() {
return stack.isEmpty();
}
// Check if stack is full
public boolean isFull() {
return stack.size() >= maxSize;
}
// Get current size
public int size() {
return stack.size();
}
// Get capacity
public int getCapacity() {
return maxSize;
}
// Display stack contents
public void display() {
if (isEmpty()) {
System.out.println("Stack is empty");
return;
}
System.out.println("Stack contents (top to bottom): " + stack);
}
}
// Usage Example:
Stack<Integer> stack = new Stack<>(10);
System.out.println("Empty: " + stack.isEmpty()); // true
System.out.println("Capacity: " + stack.getCapacity()); // 10
"""
));
codeExamples.put("Push Operation", new CodeExample(
"Push Operation",
"Add element to top of stack with overflow check",
"O(1)",
"""
// Push element to stack
public void push(T element) {
// Check for stack overflow
if (isFull()) {
throw new IllegalStateException("Stack Overflow: Cannot push to full stack");
}
// Add element to top of stack
stack.add(element);
System.out.println("Pushed: " + element + " | Size: " + size());
}
// Bulk push operation
public void pushAll(T[] elements) {
for (T element : elements) {
if (!isFull()) {
push(element);
} else {
System.out.println("Stack full! Cannot push: " + element);
break;
}
}
}
// Safe push (returns boolean instead of exception)
public boolean safePush(T element) {
if (isFull()) {
return false;
}
stack.add(element);
return true;
}
// Usage Example:
Stack<Integer> stack = new Stack<>(5);
stack.push(10);
stack.push(20);
stack.push(30);
// Stack: [10, 20, 30] (30 is top)
Integer[] values = {40, 50, 60};
stack.pushAll(values);
boolean success = stack.safePush(70); // Returns false if full
"""
));
codeExamples.put("Pop Operation", new CodeExample(
"Pop Operation",
"Remove and return top element from stack",
"O(1)",
"""
// Pop element from stack
public T pop() {
// Check for stack underflow
if (isEmpty()) {
throw new EmptyStackException();
}
// Remove and return top element
T element = stack.remove(stack.size() - 1);
System.out.println("Popped: " + element + " | Size: " + size());
return element;
}
// Safe pop (returns null instead of exception)
public T safePop() {
if (isEmpty()) {
return null;
}
return stack.remove(stack.size() - 1);
}
// Pop multiple elements
public T[] popMultiple(int count) {
if (count > size()) {
throw new IllegalArgumentException("Cannot pop more elements than stack size");
}
@SuppressWarnings("unchecked")
T[] result = (T[]) new Object[count];
for (int i = 0; i < count; i++) {
result[i] = pop();
}
return result;
}
// Usage Example:
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
int poppedElement = stack.pop(); // Returns 30
// Stack: [10, 20] (20 is now top)
Integer safePopped = stack.safePop(); // Returns 20 or null
Integer[] multiple = stack.popMultiple(2); // Pop 2 elements
"""
));
codeExamples.put("Peek Operation", new CodeExample(
"Peek Operation",
"View top element without removing it from stack",
"O(1)",
"""
// Peek at top element without removing
public T peek() {
// Check if stack is empty
if (isEmpty()) {
throw new EmptyStackException();
}
// Return top element without removing
T topElement = stack.get(stack.size() - 1);
System.out.println("Top element: " + topElement);
return topElement;
}
// Alternative: top() method (same functionality)
public T top() {
return peek();
}
// Safe peek (returns null instead of exception)
public T safePeek() {
if (isEmpty()) {
return null;
}
return stack.get(stack.size() - 1);
}
// Peek at nth element from top (0 = top, 1 = second from top, etc.)
public T peekAt(int index) {
if (index < 0 || index >= size()) {
throw new IndexOutOfBoundsException("Invalid index: " + index);
}
return stack.get(size() - 1 - index);
}
// Usage Example:
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
int topElement = stack.peek(); // Returns 30, stack unchanged
// Stack: [10, 20, 30] (30 still on top)
Integer safeTop = stack.safePeek(); // Safe version
int secondFromTop = stack.peekAt(1); // Returns 20
"""
));
// =============== STACK MANAGEMENT OPERATIONS ===============
codeExamples.put("Stack Overflow Check", new CodeExample(
"Stack Overflow Handling",
"Comprehensive overflow detection and handling mechanisms",
"O(1)",
"""
// Enhanced overflow checking with detailed reporting
public class StackOverflowManager {
// Check remaining capacity
public int getRemainingCapacity() {
return maxSize - size();
}
// Check if can accommodate n more elements
public boolean canAccommodate(int count) {
return size() + count <= maxSize;
}
// Get usage percentage
public double getUsagePercentage() {
return (double) size() / maxSize * 100;
}
// Push with overflow warning
public boolean pushWithWarning(T element, double warningThreshold) {
if (isFull()) {
System.err.println("OVERFLOW: Stack is full!");
return false;
}
push(element);
if (getUsagePercentage() >= warningThreshold) {
System.out.println("WARNING: Stack is " +
String.format("%.1f", getUsagePercentage()) + "% full");
}
return true;
}
// Auto-resize stack when near capacity
public void enableAutoResize() {
if (getUsagePercentage() >= 80) {
int newCapacity = (int) (maxSize * 1.5);
System.out.println("Auto-resizing stack from " + maxSize +
" to " + newCapacity);
maxSize = newCapacity;
}
}
}
// Usage Example:
Stack<String> stack = new Stack<>(5);
stack.pushWithWarning("A", 70.0); // Pushes and checks threshold
stack.pushWithWarning("B", 70.0);
stack.pushWithWarning("C", 70.0);
stack.pushWithWarning("D", 70.0); // Warning at 80%
System.out.println("Remaining capacity: " + stack.getRemainingCapacity());
System.out.println("Can accommodate 2 more: " + stack.canAccommodate(2));
"""
));
codeExamples.put("Stack Underflow Check", new CodeExample(
"Stack Underflow Handling",
"Comprehensive underflow detection and safe operations",
"O(1)",
"""
// Enhanced underflow checking and safe operations
public class StackUnderflowManager {
// Safe operations that handle underflow gracefully
public Optional<T> safePeek() {
return isEmpty() ? Optional.empty() : Optional.of(peek());
}
public Optional<T> safePop() {
return isEmpty() ? Optional.empty() : Optional.of(pop());
}
// Pop with default value
public T popOrDefault(T defaultValue) {
return isEmpty() ? defaultValue : pop();
}
// Conditional operations
public boolean popIf(Predicate<T> condition) {
if (isEmpty()) return false;
T top = peek();
if (condition.test(top)) {
pop();
return true;
}
return false;
}
// Bulk safe pop
public List<T> safePop(int count) {
List<T> result = new ArrayList<>();
int actualCount = Math.min(count, size());
for (int i = 0; i < actualCount; i++) {
result.add(pop());
}
if (actualCount < count) {
System.out.println("Warning: Could only pop " + actualCount +
" elements (requested: " + count + ")");
}
return result;
}
// Stack state validation
public void validateState() throws IllegalStateException {
if (size() < 0) {
throw new IllegalStateException("Invalid stack state: negative size");
}
if (stack == null) {
throw new IllegalStateException("Stack not initialized");
}
}
}
// Usage Example:
Stack<Integer> stack = new Stack<>();
// Safe operations
Optional<Integer> safeTop = stack.safePeek(); // Returns empty Optional
Optional<Integer> safePop = stack.safePop(); // Returns empty Optional
stack.push(10);
stack.push(20);
Integer value = stack.popOrDefault(-1); // Returns 20
List<Integer> values = stack.safePop(5); // Pops available elements
// Conditional pop
stack.push(15);
boolean popped = stack.popIf(x -> x > 10); // Pops if condition true
"""
));
codeExamples.put("Clear Stack", new CodeExample(
"Clear Stack Operations",
"Various methods to clear and reset stack",
"O(1)",
"""
// Clear all elements from stack
public void clear() {
stack.clear();
System.out.println("Stack cleared. Size: " + size());
}
// Clear with confirmation
public boolean clearWithConfirmation() {
if (isEmpty()) {
System.out.println("Stack is already empty");
return false;
}
int oldSize = size();
clear();
System.out.println("Cleared " + oldSize + " elements from stack");
return true;
}
// Clear and return all elements
public List<T> clearAndReturn() {
List<T> allElements = new ArrayList<>(stack);
clear();
return allElements;
}
// Selective clear (remove elements matching condition)
public int clearIf(Predicate<T> condition) {
List<T> toRemove = stack.stream()
.filter(condition)
.collect(Collectors.toList());
stack.removeAll(toRemove);
System.out.println("Removed " + toRemove.size() + " elements");
return toRemove.size();
}
// Reset stack to initial state
public void reset() {
clear();
maxSize = 100; // Reset to default capacity
System.out.println("Stack reset to initial state");
}
// Clear top n elements
public List<T> clearTop(int n) {
if (n >= size()) {
return clearAndReturn();
}
List<T> removed = new ArrayList<>();
for (int i = 0; i < n; i++) {
removed.add(pop());
}
return removed;
}
// Usage Example:
Stack<String> stack = new Stack<>();
stack.push("A");
stack.push("B");
stack.push("C");
// Different clear operations
List<String> backup = stack.clearAndReturn(); // Backup before clear
// Restore and selective clear
stack.pushAll(backup.toArray(new String[0]));
int removed = stack.clearIf(s -> s.equals("B")); // Remove specific elements
List<String> topElements = stack.clearTop(2); // Clear top 2 elements
stack.reset(); // Complete reset
"""
));
// =============== ADVANCED STACK APPLICATIONS ===============
codeExamples.put("Balanced Parentheses", new CodeExample(
"Balanced Parentheses Checker",
"Check if parentheses, brackets, and braces are properly balanced",
"O(n)",
"""
// Comprehensive balanced parentheses checker
public class BalancedParenthesesChecker {
public static boolean isBalanced(String expression) {
Stack<Character> stack = new Stack<>();
for (char ch : expression.toCharArray()) {
// Push opening brackets
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
}
// Check closing brackets
else if (ch == ')' || ch == ']' || ch == '}') {
if (stack.isEmpty()) {
return false; // No matching opening bracket
}
char top = stack.pop();
if (!isMatchingPair(top, ch)) {
return false; // Mismatched brackets
}
}
}
return stack.isEmpty(); // All brackets should be matched
}
private static boolean isMatchingPair(char open, char close) {
return (open == '(' && close == ')') ||
(open == '[' && close == ']') ||
(open == '{' && close == '}');
}
// Enhanced version with error reporting
public static class ValidationResult {
public final boolean isValid;
public final String errorMessage;
public final int errorPosition;
public ValidationResult(boolean isValid, String errorMessage, int errorPosition) {
this.isValid = isValid;
this.errorMessage = errorMessage;
this.errorPosition = errorPosition;
}
}
public static ValidationResult validateWithDetails(String expression) {
Stack<Character> stack = new Stack<>();
Stack<Integer> positions = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i);
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
positions.push(i);
}
else if (ch == ')' || ch == ']' || ch == '}') {
if (stack.isEmpty()) {
return new ValidationResult(false,
"Unmatched closing bracket '" + ch + "'", i);
}
char top = stack.pop();
positions.pop();
if (!isMatchingPair(top, ch)) {
return new ValidationResult(false,
"Mismatched brackets: '" + top + "' and '" + ch + "'", i);
}
}
}
if (!stack.isEmpty()) {
return new ValidationResult(false,
"Unmatched opening bracket '" + stack.peek() + "'", positions.peek());
}
return new ValidationResult(true, "All brackets are balanced", -1);
}
}
// Usage Examples:
System.out.println(isBalanced("({[]})")); // true
System.out.println(isBalanced("({[})")); // false
System.out.println(isBalanced("((()))")); // true
System.out.println(isBalanced("((())")); // false
ValidationResult result = validateWithDetails("({[})");
System.out.println("Valid: " + result.isValid);
System.out.println("Error: " + result.errorMessage);
System.out.println("Position: " + result.errorPosition);
"""
));
codeExamples.put("String Reversal", new CodeExample(
"String Reversal Using Stack",
"Reverse strings and validate palindromes using stack",
"O(n)",
"""
// Comprehensive string operations using stack
public class StringReverser {
// Basic string reversal
public static String reverse(String str) {
Stack<Character> stack = new Stack<>();
// Push all characters onto stack
for (char ch : str.toCharArray()) {
stack.push(ch);
}
// Pop characters to build reversed string
StringBuilder reversed = new StringBuilder();
while (!stack.isEmpty()) {
reversed.append(stack.pop());
}
return reversed.toString();
}
// Reverse words in a sentence (keep word order, reverse each word)
public static String reverseWords(String sentence) {
String[] words = sentence.split(" ");
StringBuilder result = new StringBuilder();
for (int i = 0; i < words.length; i++) {
if (i > 0) result.append(" ");
result.append(reverse(words[i]));
}
return result.toString();
}
// Reverse sentence order (reverse word order)
public static String reverseSentence(String sentence) {
Stack<String> wordStack = new Stack<>();
String[] words = sentence.split(" ");
for (String word : words) {
wordStack.push(word);
}
StringBuilder result = new StringBuilder();
boolean first = true;
while (!wordStack.isEmpty()) {
if (!first) result.append(" ");
result.append(wordStack.pop());
first = false;
}
return result.toString();
}
// Check if string is palindrome using stack
public static boolean isPalindrome(String str) {
// Remove non-alphanumeric and convert to lowercase
String cleaned = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
Stack<Character> stack = new Stack<>();
int length = cleaned.length();
// Push first half onto stack
for (int i = 0; i < length / 2; i++) {
stack.push(cleaned.charAt(i));
}
// Compare second half with popped characters
int start = (length % 2 == 0) ? length / 2 : (length / 2) + 1;
for (int i = start; i < length; i++) {
if (stack.isEmpty() || stack.pop() != cleaned.charAt(i)) {
return false;
}
}
return true;
}
// Remove adjacent duplicates
public static String removeAdjacentDuplicates(String str) {
Stack<Character> stack = new Stack<>();
for (char ch : str.toCharArray()) {
if (!stack.isEmpty() && stack.peek() == ch) {
stack.pop(); // Remove duplicate
} else {
stack.push(ch);
}
}
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.insert(0, stack.pop());
}
return result.toString();
}
}
// Usage Examples:
System.out.println(reverse("HELLO")); // "OLLEH"
System.out.println(reverseWords("Hello World")); // "olleH dlroW"
System.out.println(reverseSentence("Hello World Java")); // "Java World Hello"
System.out.println(isPalindrome("A man a plan a canal Panama")); // true
System.out.println(removeAdjacentDuplicates("abbaca")); // "ca"
"""
));
codeExamples.put("Expression Evaluation", new CodeExample(
"Mathematical Expression Evaluation",
"Evaluate infix, postfix, and prefix expressions using stack",
"O(n)",
"""
// Comprehensive expression evaluator
public class ExpressionEvaluator {
// Evaluate postfix expression
public static double evaluatePostfix(String expression) {
Stack<Double> stack = new Stack<>();
String[] tokens = expression.trim().split("\\s+");
for (String token : tokens) {
if (isOperator(token)) {
if (stack.size() < 2) {
throw new IllegalArgumentException("Invalid postfix expression");
}
double operand2 = stack.pop();
double operand1 = stack.pop();
double result = performOperation(operand1, operand2, token);
stack.push(result);
} else {
try {
double operand = Double.parseDouble(token);
stack.push(operand);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid number: " + token);
}
}
}
if (stack.size() != 1) {
throw new IllegalArgumentException("Invalid postfix expression");
}
return stack.pop();
}
// Convert infix to postfix
public static String infixToPostfix(String infix) {
StringBuilder postfix = new StringBuilder();
Stack<Character> operatorStack = new Stack<>();
for (char ch : infix.toCharArray()) {
if (Character.isDigit(ch) || Character.isLetter(ch)) {
postfix.append(ch).append(' ');
}
else if (ch == '(') {
operatorStack.push(ch);
}
else if (ch == ')') {
while (!operatorStack.isEmpty() && operatorStack.peek() != '(') {
postfix.append(operatorStack.pop()).append(' ');
}
operatorStack.pop(); // Remove '('
}
else if (isOperator(String.valueOf(ch))) {
while (!operatorStack.isEmpty() &&
getPrecedence(operatorStack.peek()) >= getPrecedence(ch)) {
postfix.append(operatorStack.pop()).append(' ');
}
operatorStack.push(ch);
}
}
while (!operatorStack.isEmpty()) {
postfix.append(operatorStack.pop()).append(' ');
}
return postfix.toString().trim();
}
// Evaluate infix expression directly
public static double evaluateInfix(String infix) {
String postfix = infixToPostfix(infix);
return evaluatePostfix(postfix);
}
private static boolean isOperator(String token) {
return token.equals("+") || token.equals("-") ||
token.equals("*") || token.equals("/") ||
token.equals("^");
}
private static int getPrecedence(char operator) {
switch (operator) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default:
return 0;
}
}
private static double performOperation(double a, double b, String operator) {
switch (operator) {
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/":
if (b == 0) throw new ArithmeticException("Division by zero");
return a / b;
case "^": return Math.pow(a, b);
default: throw new IllegalArgumentException("Unknown operator: " + operator);
}
}
}
// Usage Examples:
// Postfix evaluation
System.out.println(evaluatePostfix("2 3 + 4 *")); // (2+3)*4 = 20
System.out.println(evaluatePostfix("15 7 1 1 + - / 3 * 2 1 1 + + -")); // Complex expression
// Infix to postfix conversion
System.out.println(infixToPostfix("2+3*4")); // "2 3 4 * +"
System.out.println(infixToPostfix("(2+3)*4")); // "2 3 + 4 *"
// Direct infix evaluation
System.out.println(evaluateInfix("(2+3)*4-1")); // 19.0
"""
));
codeExamples.put("Function Call Stack", new CodeExample(
"Function Call Stack Simulation",
"Simulate function call stack for recursion and debugging",
"O(n)",
"""
// Function call stack simulator
public class CallStackSimulator {
public static class StackFrame {
public final String functionName;
public final Map<String, Object> localVariables;
public final List<Object> parameters;
public final int lineNumber;
public StackFrame(String functionName, int lineNumber) {
this.functionName = functionName;
this.lineNumber = lineNumber;
this.localVariables = new HashMap<>();
this.parameters = new ArrayList<>();
}
public void addVariable(String name, Object value) {
localVariables.put(name, value);
}
public void addParameter(Object value) {
parameters.add(value);
}
@Override
public String toString() {
return String.format("%s(line %d) - Vars: %s, Params: %s",
functionName, lineNumber, localVariables, parameters);
}
}
private static Stack<StackFrame> callStack = new Stack<>();
// Function entry
public static void enterFunction(String functionName, int lineNumber) {
StackFrame frame = new StackFrame(functionName, lineNumber);
callStack.push(frame);
System.out.println("CALL: " + functionName + " at line " + lineNumber);
printCallStack();
}
// Function exit
public static void exitFunction(Object returnValue) {
if (!callStack.isEmpty()) {
StackFrame frame = callStack.pop();
System.out.println("RETURN: " + frame.functionName +
" returns " + returnValue);
}
}
// Add variable to current frame
public static void addVariable(String name, Object value) {
if (!callStack.isEmpty()) {
callStack.peek().addVariable(name, value);
}
}
// Print current call stack
public static void printCallStack() {
System.out.println("=== Call Stack ===");
Stack<StackFrame> temp = new Stack<>();
// Print from top to bottom
while (!callStack.isEmpty()) {
StackFrame frame = callStack.pop();
System.out.println(" " + frame);
temp.push(frame);
}
// Restore original stack
while (!temp.isEmpty()) {
callStack.push(temp.pop());
}
System.out.println("==================");
}
// Recursive factorial with call stack tracking
public static long factorial(int n) {
enterFunction("factorial", 1);
addVariable("n", n);
if (n <= 1) {
exitFunction(1L);
return 1;
}
long result = n * factorial(n - 1);
addVariable("result", result);
exitFunction(result);
return result;
}
// Fibonacci with call stack tracking
public static long fibonacci(int n) {
enterFunction("fibonacci", 1);
addVariable("n", n);
if (n <= 1) {
exitFunction((long)n);
return n;
}
long result = fibonacci(n - 1) + fibonacci(n - 2);
addVariable("result", result);
exitFunction(result);
return result;
}
}
// Usage Examples:
System.out.println("=== Factorial Call Stack ===");
long fact = CallStackSimulator.factorial(4);
System.out.println("Result: " + fact);
System.out.println("\\n=== Fibonacci Call Stack ===");
long fib = CallStackSimulator.fibonacci(3);
System.out.println("Result: " + fib);
"""
));
// =============== DIFFERENT STACK IMPLEMENTATIONS ===============
codeExamples.put("Array-Based Stack", new CodeExample(
"Array-Based Stack Implementation",
"Fixed-size stack implementation using arrays",
"O(1) for all operations",
"""
// Array-based stack implementation
public class ArrayStack<T> {
private Object[] stack;
private int top;
private final int maxSize;
public ArrayStack(int capacity) {
this.maxSize = capacity;
this.stack = new Object[capacity];
this.top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize - 1;
}
public int size() {
return top + 1;
}
public void push(T element) {
if (isFull()) {
throw new RuntimeException("Stack Overflow");
}
stack[++top] = element;
}
@SuppressWarnings("unchecked")
public T pop() {
if (isEmpty()) {
throw new RuntimeException("Stack Underflow");
}
T element = (T) stack[top];
stack[top--] = null; // Help GC
return element;
}
@SuppressWarnings("unchecked")
public T peek() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return (T) stack[top];
}
// Display stack contents
public void display() {
if (isEmpty()) {
System.out.println("Stack is empty");
return;
}
System.out.print("Stack (top to bottom): ");
for (int i = top; i >= 0; i--) {
System.out.print(stack[i] + " ");
}
System.out.println();
}
// Get all elements as array
@SuppressWarnings("unchecked")
public T[] toArray() {