Stack
- 스택으로 reverseString 구현
package adt;
// Stack 클래스
public class Stack {
private char [] myStack;
private int maxSize;
private int top = -1;
Stack(int s) {
this.maxSize = s;
myStack = new char [maxSize];
}
public void push(char i) {
top++;
myStack[top] = i;
}
public char pop() {
int old_top = top;
top--;
return myStack[old_top];
}
public boolean isEmpty() {
if(top == -1) {
return true;
}
return false;
}
public boolean isFull() {
if(top == maxSize) {
return true;
}
return false;
}
public int getTop() {
return top;
}
}
// 메서드를 통한 출력
package adt;
public class App {
public static void main(String[] args) {
System.out.println(reverseStr("hello"));
}
public static String reverseStr(String str) {
int len = str.length();
Stack stack = new Stack(len);
for(int i = 0 ; i < len ; i++) {
char ch = str.charAt(i);
stack.push(ch);
}
String result = "";
while(!stack.isEmpty()) {
result += stack.pop();
}
return result;
}
}