BackEnd/Java
Stack과 Queue
ejyoovV
2021. 3. 6. 15:15
📝 잦은 데이터 삭제가 있는 경우 LinkedList가 좋음.
- Stack : 후입선출(LIFO)의 자료구조
- Queue : 선입선출(FIFO)의 자료구조
📝 Stack과 Queue는 LinkedList를 이용하여 사용할 수 있다.
💡 Stack의 명령 : 자료 입력 push()
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> stack = new LinkedList<>();
stack.push("홍길동");
stack.push("일지매");
stack.push("변학도");
stack.push("강감찬");
System.out.println("Stack 값 출력 : " + stack);
}
}
💡 Stack의 명령 : 자료 출력 pop()
자료를 꺼내온 후 꺼내온 자료를 Stack에서 삭제한다.
package baekjoonProject;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> stack = new LinkedList<>();
stack.push("홍길동");
stack.push("일지매");
stack.push("변학도");
stack.push("강감찬");
System.out.println("1. Stack 값 출력 : " + stack);
// 1) 꺼낸 뒤 String 변수에 담는 방법
String data = stack.pop();
System.out.println("꺼내온 자료 : " + data);
// 2) 꺼내고 바로 출력하는 방법
System.out.println("꺼내온 자료 : " + stack.pop());
System.out.println("2. Stack 값 출력 : " + stack);
}
}
💡 Queue의 명령 : 자료 입력 offer()
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> queue = new LinkedList<>();
queue.offer("홍길동");
queue.offer("일지매");
queue.offer("변학도");
queue.offer("강감찬");
System.out.println("1. queue 값 출력 : " + queue);
}
}
💡 Queue의 명령 : 자료 출력 poll()
자료를 꺼내온 후 꺼내온 자료는 Queue에서 삭제한다.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> queue = new LinkedList<>();
queue.offer("홍길동");
queue.offer("일지매");
queue.offer("변학도");
queue.offer("강감찬");
System.out.println("1. queue 값 출력 : " + queue);
//1) 꺼낸 뒤 String 변수에 담는 방법
String data = queue.pop();
System.out.println("꺼내온 자료 : " + data);
//2) 꺼내고 바로 출력하는 방법
System.out.println("꺼내온 자료 : " + queue.pop());
System.out.println("2. queue 값 출력 : " + queue);
}
}