kotlin/java
Stack & Queue
slow333
2023. 1. 6. 12:54
class stack => last in first out , LIFO , push/pop, ArrayList
| 2 | => pop
| 1 |
| 0 |
|____________ |
interface queue => first in first out, FIFO, offer/poll/peek, LinkedList(삭제시 자리이동 없음)
add(Object o), remove(), element() 읽기 ; 예외발생
Queue q = new LinkedList();
LinkedList ll = new LinkedList();
import java.util.*;
public class StackAndQueueEx {
static final int MAX_SIZE = 5;
static Queue<String> q = new LinkedList<>();
public static void main(String[] args) {
Collection<Integer> list = new HashSet<>();
list.add(1); list.add(2); list.add(3); list.add(4); list.add(5);
for (Integer integer : list)
System.out.println(integer);
Map<String, Integer> map = new HashMap<>();
map.put("1", 10);
map.put("2", 20);
map.put("4", 40);
map.put("5", 50);
System.out.println(map.keySet()+" : "+map.values());
System.out.println(map.entrySet());
Stack<String> st = new Stack<>();
String expression = "(2+3)*2 + (3/3)";
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.empty()) System.out.println("정상 수식");
else System.out.println("비 정상 수식");
} catch (Exception e){
System.out.println("비 정상 수식, by exception");
}
System.out.println("help는 도움말");
while (true) {
System.out.println(">>>>");
try{
Scanner sc = new Scanner(System.in);
String input = sc.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<String> lList = (LinkedList<String>) q;
int i=1;
for (String str : lList)
System.out.println((i++)+" : "+ str);
} else {
save(input);
System.out.println(input);
}
} catch (Exception ignored){}
}
}
private static void save(String input) {
if (!"".equals(input)) q.offer(input);
if (q.size() > MAX_SIZE) q.poll();
}
}