쌍용교육(JAVA)/JAVA

쌍용교육 -JAVA 수업 14일차 Stack스택(LIFO 후입선출),Queue(FIFO 선입선출)

구 승 2024. 4. 12. 08:46

Stack스택(LIFO 후입선출)

package kr.s27.collection;

import java.util.Stack;

public class StackMain {
	public static void main(String[] args) {
		//스택(Stack) :후입선출 LIFO(Last-In First-Out) 방식
		String[] array = {"진달래","백합","개나리","벚꽃","장미"};
		
		Stack<String> stk = new Stack<String>(); //Stack은 util 패키지에 있어서 호출이 필요
		//반복문을 이용해서 Stack에 요소 저장
		for(int i = 0; i <array.length; i++) {
			stk.push(array[i]); //객체를 저장 .push()를 사용해서
		}
		//저장된 요소의 목록
		System.out.println(stk);
		System.out.println("----------------------------");
		
		//현재스택이 비어있는지 검증
		while(!stk.isEmpty()) {//!를 넣었기 때문에 비어있지않으면 true인것 원래는 비어있으면 true임
			System.out.print(stk.pop()+"\\t");//pop은 스택에 저장된 객체를 꺼낸다. 즉 여기선 꺼내서 출력하는것
		}
		System.out.println("\\n----------------------------");
		System.out.println(stk);//pop을통해 stk안에 있던 것들이 다 빠지고 빈 리스트만 남았음.
	}
}

[진달래, 백합, 개나리, 벚꽃, 장미]
----------------------------
장미	벚꽃	개나리	백합	진달래	
----------------------------
[]

Queue(FIFO 선입선출)

package kr.s27.collection;

import java.util.LinkedList;

public class QueueMain {
	public static void main(String[] args) {
		//큐(Queue) : 선입선출 FIFO(First-In First-Out)
		String[] array = {"서울","부산","대구","광주","인천"};
		
		LinkedList<String> linked = new LinkedList<String>();
		
		for(int i=0; i<array.length; i++) {
			//LinkedList에 요소를 저장
			linked.offer(array[i]); //stack에서는 push와 비슷
			
		}
		//저장된 요소의 목록
		System.out.println(linked);
		System.out.println("---------------------------");
		
		//peek은 큐에 저장된 첫번째 요소를 검색 ( != null이기 떄문에 무언가 있을 떄 true반환)
		while(linked.peek() != null) {
			System.out.print(linked.poll()+"\\t");//poll은 큐에서 첫번째 요소를 반환하고 제거하는 용도
								  //stack에 pop과 비슷한 용도
		}
		System.out.println("\\n------------------------------");
		System.out.println(linked);
	}
}

[서울, 부산, 대구, 광주, 인천]
---------------------------
서울	부산	대구	광주	인천	
------------------------------
[]