1. 程式人生 > >一、實現一個特殊的棧,在實現棧的基本功能的基礎上,再實現返回棧中最小元素的操作

一、實現一個特殊的棧,在實現棧的基本功能的基礎上,再實現返回棧中最小元素的操作

empty util run print pri ont com res 字符串

請指教交流!

 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 }

一、實現一個特殊的棧,在實現棧的基本功能的基礎上,再實現返回棧中最小元素的操作