개인공부
스택과 큐의 활용
리승우
2022. 8. 16. 23:59
스택활용
import java.util.*;
public class ex11_3 {
public static void main(String[] args) {
Stack st = new Stack();
String expression = "((3+5)*8-2)";
System.out.println("expression:" + expression);
try {
for(int i=0; i< expression.length(); i++) {
char ch = expression.charAt(i); // charAt = expression문자열의 i번째 문자를 char로 뽑아냄
if (ch == '(') {
st.push(ch+"");
}else if (ch == ')') {
st.pop();
}
}
// 스택이 비어있으면,
if (st.isEmpty()) {
System.out.println("괄호가 일치합니다");
} else {
System.out.println("괄호가 일치하지 않습니다");
}
// try-catch 문구로 예외처리하는 것임
// EmptyStackException는 예외상황 클래스임 (아무거나 막 적는 것 아님) e는 다른 걸로 대체기재가능
// public class EmptyStackException
// extends RuntimeException
// EmptyStackException = Stack 클래스의 메서드에 의해 예외가 발생되어 그 스택이 비어있는 것을 나타냅니다.
// 예외발생시 아래 문구 출력됨
} catch (EmptyStackException e) {
System.out.println("괄호가 일치하지 않습니다");
}
}
}
//출력값
expression:((3+5)*8-2)
괄호가 일치합니다
큐 활용
import java.util.*;
public class ex11_4 {
static Queue q = new LinkedList();
static final int MAX_SIZE = 5; //Queue에 최대 5개까지만 저장되도록 했다
public static void main(String[] args) {
System.out.println("help를 입력하면 도움말을 볼 수 있습니다");
while(true) {
System.out.println(">>");
try {
//화면으로부터 라인단위로 입력받는다.
Scanner sc = new Scanner(System.in);
// nextLine()과 next()메소드의 차이는 nextLine()메소드는 Enter를 치기 전까지
// 쓴 문자열을 모두 리턴한다는 것이고 next() 메소드는 스페이스,
// 즉 공백 전까지 입력받은 문자열을 리턴한다는 것이다.
String input = sc.nextLine().trim();
//만약 입력한 내용이 없으면 continue > 아래 실행은 안 하고 while true로 돌아가는 것
if("".equals(input)) continue;
if(input.equalsIgnoreCase("q")) {
// 프로그램 강제종료 할때는 exit 메서드를 쓴다
// System.exit(0); //정상종료
// System.exit(1); //비정상종료
System.exit(0);
// equals 는 대소문자를 비교하지만 equalsIgnoreCases는 대소문자 구분없이 비교한다.
} else if(input.equalsIgnoreCase("help")) {
System.out.println(" help - 도움말을 보여줍니다.");
System.out.println(" q 또는 Q - 프로그램을 종료합니다.");
System.out.println(" history - 최근에 입력한 명령어를"+MAX_SIZE+"개 보여줍니다");
} else if(input.equalsIgnoreCase("history")) {
save(input); // 입력받은 명령어 저장하고,
// LinkedList의 내용을 보여준다
// LinkedList로 형변환을 하였음
LinkedList list = (LinkedList)q;
final int SIZE = list.size();
for(int i=0; i<SIZE;i++)
System.out.println((i+1)+"."+list.get(i));
} else {
save(input);
System.out.println(input);
}
} catch(Exception e) {
System.out.println("입력 오류입니다");
}
} //while(true)끝
} // main() 끝
private static void save(String input) {
//queue에 저장한다.
if(!"".equals(input))
q.offer(input); //queue에 명령어를 저장
// queue의 최대 크기를 넘으면 제일 처음 입력된 것을 삭제한다.
if(q.size() > MAX_SIZE) //size()는 Collection인터페이스에 정의
q.remove();
}
} // end of class
출력값
help를 입력하면 도움말을 볼 수 있습니다
>>
help
help - 도움말을 보여줍니다.
q 또는 Q - 프로그램을 종료합니다.
history - 최근에 입력한 명령어를5개 보여줍니다
>>
asdf
asdf
>>
fdsa
fdsa
>>
asdf
asdf
>>
qwe
qwe
>>
t4ew
t4ew
>>
History
1.fdsa
2.asdf
3.qwe
4.t4ew
5.History
>>