[IT]/java
java.stack/queue
givemebro
2021. 3. 9. 09:35
반응형

Stack : Last In First Out(LIFO)
마지막에 추가된 요소가 먼저 추출되는 자료구조
Queue : First In First Out(FIFO)
먼저 추가된 요소가 먼저 출력되는 자료구조
Stack
package step1;
import java.util.Stack;
public class TestStack {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
stack.push("a");
stack.push("b");
stack.push("c");
System.out.println(stack);
// [a, b, c]
System.out.println(stack.pop());
// c
System.out.println(stack);
// [a, b]
System.out.println(stack.isEmpty());
// false
// while문을 이용해서 모든 요소를 pop()으로 추출하고 종료
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
// b
// a
System.out.println(stack.isEmpty());
// true
}
}
Queue
package step1;
import java.util.LinkedList;
import java.util.Queue;
public class TestQueue {
public static void main(String[] args) {
// LinkedList list = new LinkedList();
// queue: 메세지 처리할 때 주로 사용
Queue<String> queue = new LinkedList<String>();
queue.add("경성오빠 안녕~~");
queue.add("어디야?");
queue.add("대답안해!!");
queue.add("헤어져~");
System.out.println(queue.poll());
// 경성오빠 안녕~~
System.out.println(queue.isEmpty());
// false
while(!queue.isEmpty()) {
System.out.println(queue.poll());
}
// 어디야?
// 대답안해!!
// 헤어져~
}
}
Java Platform SE 7
docs.oracle.com
반응형