Java棧類實現:
public class StackExercise { Object[] stacks; // 棧容器 int size; // 棧容量 int top; // 記錄位置 int len; // 棧實際成員數量 public StackExercise(int size) { super(); this.size = size; this.stacks = new Object[this.size]; this.top = -1; } // 獲取棧頂元素 public Object peek() { return this.stacks[top]; } // 判斷棧是否為空 public boolean isEmpty() { return top == (-1); } // 判斷棧是否已滿 public boolean isFull() { return top == (size - 1); } // 入棧過程 public void push(Object value) { len++; stacks[++this.top] = value; } // 出棧過程 public Object pop() { len--; return stacks[this.top--]; // 注意這里不能用“--this.top”,會導致棧溢出 } // 獲取棧實際大小 public int len() { return this.len; } }
實現進制轉換:
public class TestStack { // 二進制轉換方法 public static String toJinzhi(int num) { StackExercise stack = new StackExercise(32); while (num > 0) { stack.push(num % 2); num = num / 2; } StringBuffer sBuffer = new StringBuffer(); while (!stack.isEmpty()) { sBuffer.append(stack.pop()); } return sBuffer.toString(); } // 通用進制轉換方法 public static String baseConvert(int num, int base) { StackExercise stack = new StackExercise(32); while (num > 0) { stack.push(num % base); num = num / base; } String dights = "0123456789abcdef"; StringBuffer sBuffer = new StringBuffer(); while (!stack.isEmpty()) { sBuffer.append(String.valueOf(dights.charAt((int) stack.pop()))); } return sBuffer.toString(); } public static void main(String[] args) { System.out.println(toJinzhi(123456789)); System.out.println(baseConvert(255, 2)); } }