[자바] 스택 소스코드

BEHE_LIT·2020년 1월 3일
0

자료구조

목록 보기
2/14
import java.util.EmptyStackException;
public 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 StackExample {

	public static void main(String[] args) {
		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());

	}

}

profile
방랑자의 현장에 오신걸 환영합니다.

0개의 댓글