다연이네

[days22] 컬렉션 클래스<List> - Stack과 Queue 본문

Java

[days22] 컬렉션 클래스<List> - Stack과 Queue

 다연  2020. 10. 21. 09:30
반응형

스택(Stack)과 큐(Queue)
 ㄱ. 스택
   1) LIFO구조 - Last In First Out - 마지막에 저장된 데이터가 가장 먼저 꺼내지는 구조
   2) Collection -> List -> Vector 클래스 -> Stack 클래스
                               (스택클래스는 벡터클래스를 상속받는다)

ㄴ. 큐
   1) FIFO구조 - First In First Out - 처음에 저장된 데이터가 가장 먼저 꺼내지는 구조

 

 

스택

push(), pop(), peek(), empty()

- 집어넣을때 push() 꺼낼때 peek()/pop()      add사용금지

Stack<String> list = new Stack<String>();

list.push("김동준");
list.push("이동준");
list.push("박동준");

System.out.println(list.pop());  //박동준 pop(): 제거하고 끄집어 냄
System.out.println(list.peek()); //이동준 제거 안하고 끄집어내기만
System.out.println(list.peek()); //이동준

offer(), poll(), peek(), empty()

Queue<String> q =  new LinkedList<>(); // LinkedList는 큐가 구현된 클래스이다. !!

q.offer("홍길동");
q.offer("김길동");
q.offer("박길동");

System.out.println(q.poll()); //홍길동 제거하고 끄집
System.out.println(q.peek()); //김길동
System.out.println(q.peek()); //김길동

PriorityQueue

FIFO가 아니라 우선권이 높은 것이 먼저 나오는 구조

PriorityQueue<Integer> pq = new PriorityQueue<>(); 

pq.offer(3);
pq.offer(1);
pq.offer(5);
pq.offer(4);
pq.offer(2);


Integer value = -1;
	while ((value =pq.poll())!=null) {  //int와 null 비교 불가 => Integer로 교체(언박싱하지 않으면 null값 처리 가능)
		System.out.println(value);
	} // 1  2  3  4  5  출력
    
   	 //추측 - 숫자는 작은 값이 우선순위가 높다라고 인식
	//다른 new Student(); new BoardVO()등은 개발자가 직접 우선순위를 구현해야 함

Deque

Queue의 변형으로 한쪽 끝으로만 추가/삭제할수 있는 일반적인 큐와 달리 양쪽 끝에 추가/삭제가 가능하다.

디큐의 조상이 큐이다.

디큐를 구현한 클래스 LinkedList, ArrayDeque

offerLast() ->  pollFirst() : 끝에 저장 앞에서 삭제
offerFirst() -> pollLast() : 앞에 저장 끝에서 삭제

		ArrayList<String> list = new ArrayList<String>();
		list.add("A");
		list.add("B");
		list.add("C");
		list.add("D");
		
		System.out.println(list.size()); //4
		
			//list.iterator() 단방향
		ListIterator<String>  ir = list.listIterator(); //양방향
		while (ir.hasNext()) {
			String one = ir.next();
			System.out.println(one);
		} 
       		 // A			B		C		D 출력
		
		
		while (ir.hasPrevious()) { //이전에 데이터가 있니?
			String one = ir.previous();//이전 데이터 읽어오기
 			System.out.println(one);
		} 
     		   // D			C		B		A 출력
반응형
Comments