请指教交流!
1 package com.it.hxs.c01; 2 3 import java.util.Stack; 4 5 /* 6 实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作 7 */ 8 public class GetMinStack { 9 10 public static void main(String args[]) { 11 GetMinStack demoStack = new GetMinStack(); 12 demoStack.push("1"); 13 demoStack.push("2"); 14 demoStack.push(""); 15 System.out.println(demoStack.getMin()); 16 System.out.println(demoStack.pop()); 17 System.out.println(demoStack.getMin()); 18 } 19 20 private Stack<String> stringStack; 21 private Stack<Integer> intStack; 22 private Stack<String> minStack; 23 24 public GetMinStack() { 25 this.stringStack = new Stack<String>(); 26 this.intStack = new Stack<Integer>(); 27 this.minStack = new Stack<String>(); 28 } 29 30 public void push(String content) { 31 if ("".equals(content)||content == null) { 32 throw new RuntimeException("添加的元素值不能为空!"); 33 } else { 34 int data = string2ASCII(content); 35 stringStack.push(content); 36 if (!intStack.isEmpty()) { 37 int curIntStackData = intStack.peek(); 38 if (curIntStackData >= data) {// 数值栈intStack中最上面元素大于当前推入元素,则当前元素为最小,则当前元素推入最小元素栈minStack 39 minStack.push(content); 40 } else { 41 minStack.push(minStack.peek()); 42 } 43 } else { 44 minStack.push(content); 45 } 46 intStack.push(data); 47 } 48 } 49 50 public String pop() { 51 String result = "无元素"; 52 if (!intStack.isEmpty()) { 53 intStack.pop(); 54 } 55 if (!minStack.isEmpty()) { 56 minStack.pop(); 57 } 58 if (!stringStack.isEmpty()) { 59 result = stringStack.pop(); 60 } 61 return result; 62 } 63 64 public String getMin() { 65 String result = "无元素"; 66 if (!minStack.isEmpty()) { 67 result = minStack.peek(); 68 } 69 return result; 70 } 71 72 // 字符串转ASCII 73 public static int string2ASCII(String content) { 74 int result = 0; 75 char[] chars = content.toCharArray(); 76 for (char c : chars) { 77 int temp = (int) c; 78 result = result + temp; 79 } 80 return result; 81 } 82 83 }
时间: 2024-10-19 14:17:44