스택의 활용 : 수식계산, 수식괄호검사, 워드프로세서의 undo/redo, 웹브라우저의 뒤로/앞으로
큐의 활용 : 최근 사용 문서, 인쇄 작업 대기 목록, 버퍼(buffer)
import java.util.*;
public class Stack_Queue {
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);
if(ch == '(') {
st.push(ch + "");
}else if(ch == ')') {
st.pop();
}
}
if(st.isEmpty()) {
System.out.println("괄호가 일치합니다.");
}else {
System.out.println("괄호가 일치하지 않습니다.");
}
} catch (EmptyStackException e) {
System.out.println("괄호가 일치하지 않습니다.");
}
}
}
--> 스택
import java.util.*;
public class Stack_Queue {
static Queue q = new LinkedList();
static final int MAX_SIZE = 5;
public static void main(String[] args) {
System.out.println("help를 입력하면 도움말을 볼 수 있습니다.");
while(true) {
System.out.println(">>");
try {
Scanner s = new Scanner(System.in);
String input = s.nextLine().trim();
if("".equals(input)) continue;
if(input.equalsIgnoreCase("q")) {
System.exit(0); // 프로그램 종료
}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 list = (LinkedList)q;
final int SIZE = list.size();
for(int i = 0; i<list.size(); i++)
System.out.println((i+1) + "." + list.get(i));
}else {
save(input);
System.out.println(input);
}
}catch(Exception e) {
System.out.println("입력오류입니다.");
}
}
}
public static void save(String input) {
if(!"".equals(null))
q.offer(input);
if(q.size() > MAX_SIZE)
q.remove();
}
}
--> 큐