Preparing Coding Test/Algorithm
[Java/자료구조] Stack 구현하기
weero
2020. 9. 3. 12:00
https://www.youtube.com/watch?v=whVUYv0Leg0&t=9s
LIFO (Last In First Out)
1) pop() : 마지막에 넣은 데이터를 가져오면서 지우는 함수
2) push() : 한 개 더 쌓아올리는 함수
3) peek() : 맨 위에 있는 걸 확인하는 함수
4) isEmpty() : Stack이 비어있는지 확인하기
코드
import java.util.EmptyStackException;
class Stack<T>{
class Node<T>{
private T data;
private Node<T> next;
public Node(T data) {
this.data = data;
}
}
private Node<T> top;
public T pop() {
if(top==null)
throw new EmptyStackException();
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 EmptyStackException();
return top.data;
}
public boolean isEmpty() {
return top==null;
}
}
public class Main{
public static void main(String[] args) throws IOException{
Stack<Integer> 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());
}
}