풀스택/java

Java _ Stack 과 Queue 이해

lsme 2022. 4. 29. 18:54

 

1. Stack, Last in First Out (LIFO) : 마지막에 들어온 값이 첫번째로 나간다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.Stack;
 
public class StackTest {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] stackArray = {"벤츠""아우디""현대""bmw""람보르기니"};
        
        Stack<String> stack = new Stack<String>();
        for(String carName : stackArray) {
            stack.push(carName);
        }
        
        while(!stack.isEmpty()) {
            //isEmpty : Collection 인터페이스에서 제공
            //요소가 없으면 true 반환
            
            System.out.println(stack.pop());
        }        
    }
}
cs

 

<결과값>


 

2. Queue, First In First Out(FIFO) : 첫번째로 나온 값이 첫번째로 나간다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.LinkedList;
 
public class QueueTest {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] QueueArray = {"개나리""난초""코스모스""장미"};
        
        LinkedList<String> queue = new LinkedList<String>();
        
        for(String flower : QueueArray) {
            queue.offer(flower);
        }
        System.out.println("queue의 크기" + queue.size());
        
        String data = " ";
        while((data = queue.poll()) != null) {
            System.out.println(data);
        }
        System.out.println("queue의 크기: " + queue.size() ); //while에서 다씀.
 
    }
}
cs

<결과 창>