Mega Code Archive

 
Categories / Java / Collections Data Structure
 

Triangular numbers with stack replaces recursion

import java.io.IOException; public class TriangleStack {   static int num;   static int ans;   static Stack theStack;   public static void main(String[] args) throws IOException {     num = 100;     stackTriangle();     System.out.println("Triangle=" + ans);   }   public static void stackTriangle() {     theStack = new Stack(10000); // make a stack     ans = 0; // initialize answer     while (num > 0) // until n is 1,     {       theStack.push(num); // push value       --num; // decrement value     }     while (!theStack.isEmpty()) // until stack empty,     {       int newN = theStack.pop(); // pop value,       ans += newN; // add to answer     }   } } class Stack {   private int maxSize; // size of stack array   private int[] data;   private int top; // top of stack   public Stack(int s) {     maxSize = s;     data = new int[maxSize];     top = -1;   }   public void push(int p) {     data[++top] = p;   }   public int pop() {     return data[top--];   }   public int peek() {     return data[top];   }   public boolean isEmpty() {     return (top == -1);   } }