《Java数据结构与算法》笔记-CH4-2用栈实现字符串反转

import java.io.BufferedReader;
import java.io.InputStreamReader; //用栈来实现一个字符串逆序算法
/**
* 数据结构:栈
*/
class StackW{
private int maxSize;
private char[] stackArray;
private int top;
public StackW(int max){
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char c){
stackArray[++top] = c;
}
public char pop(){
return stackArray[top--];
}
public char peek(){
return stackArray[top];
}
public boolean isEmpty(){
return (top == -1);
}
public boolean isFull(){
return (top == maxSize);
}
}
/**
* 反转类
*/
class Reverser{
private String input;
private StringBuilder output;
public Reverser(String in){
input = in;
output = new StringBuilder();
}
/**
* 使用定义的栈来进行字符串的反转
* @return
*/
public String doReverse(){
int stackSize = input.length();
StackW s = new StackW(stackSize);
for(int j= 0;j<stackSize;j++){
char c = input.charAt(j);
s.push(c);
}
while(!s.isEmpty()){
char ch = s.pop();
output.append(ch);
}
return output.toString();
}
}
public class WordReverse {
public static void main(String[] args) throws Exception {
String input, output;
while(true){
System.out.println("Enter a string");
System.out.flush();
input = getString();
if(input.equals(""))
break;
Reverser re = new Reverser(input);
output = re.doReverse();
System.out.println("reversed:"+output);
}
}
/**
* 从键盘读字符串
* @return
* @throws Exception
*/
public static String getString() throws Exception{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
}
上一篇:全球及中国片式多层陶瓷电容器(MLCC)行业发展格局与投资策略研究报告2022版


下一篇:浅谈TabLayout(ViewPager+Tab联动)