[자바] 자료구조 스택

BEHE_LIT·2020년 1월 3일
0

자료구조

목록 보기
1/14
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(); 
		}
		//맨위에 있는 데이터를 반환하기전에 그 다음주소에 있는 변수를 TOP으로 만들어줘야한다
		T item = top.data; //데이터를 백업
		top = top.next; //다음 데이터를 top으로 만들어준다
		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개의 댓글