CS지식/자료구조

TIL 정리_50(Stack)

ran4 2022. 4. 6. 20:46

 

Stack 

 

stack : 쌓다

LIFO(Last In First Out) 구조이다

바로 넣었다가 거꾸로 정렬된 데이터를 꺼내쓰고 싶을 때 유용하다

 

지원하는 기능

  • pop() : 맨 마지막에 넣은 데이터를 가져오면서 지운다
  • push() : 새로운 데이터를 맨 위에 쌓아 올리는 것이다
  • peek() : 맨 마지막 데이터를 본다
  • isEmpty() : 스택에 데이터가 있는지 없는지 확인한다

 

 

 

stack 코드로 구현

import java.util.EmptyStackException;


class Stack<T> {
class Node<T> {
private T data;
private Node<T> data;


public Node(T data) {
this.data = data;
}
}
private Node<T> top;


public T pop() {
if( top == null) {
throw new ExptyStackException();
}


T item = top data;
top = top.next;
return item;
}
public void push(T item) {
Node<T> t = new Node<T>(item);
t.next = top;
top = t;
}
public T peek() {
if (top == null) {
throw new ExptyStackException();
}
return top.data;
}


public boolean isEmpty() {
return top == null;
}
}

public class Test {
public static void main (String[] args) {
Stack<Integet> s = new Stack<Integer>();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
System.out.println(s.pop()); //마지막에 넣은 데이터를 가져오면서 지운다
System.out.println(s.pop());
System.out.println(s.peek()); //마지막 데이터 조회
System.out.println(s.pop());
System.out.println(s.isEmpty()); //스택에 데이터가 있는지 확인
System.out.println(s.pop());
System.out.println(s.isEmpty());
}
}

 

'CS지식 > 자료구조' 카테고리의 다른 글

TIL 정리_56  (0) 2022.04.12
TIL 정리_51(Queue)  (0) 2022.04.07
TIL 정리_49(StringBuilder)  (0) 2022.04.05
TIL 정리_48(Hash Table, ArrayList)  (0) 2022.04.04
TIL 정리_47(Linked List)  (0) 2022.04.03