본문 바로가기
알고리즘 & 자료구조/자료구조-Java

Stack 구현

by 신재권 2021. 7. 14.
package review1;

import java.util.ArrayList;

public class StackImplement<T> {
	private ArrayList<T> stack = new ArrayList<T>();
	
	public void push(T item){
		stack.add(item);
	}
	
	//데이터 삭제
	public T pop(){
		if(stack.isEmpty()){
			return null;
		}
		return stack.remove(stack.size()-1);
	}
	
	public boolean isEmpty(){
		return stack.isEmpty();
	}
	
	//맨 위에 있는 데이터 반환
	public T peek(){
		return stack.get(stack.size()-1);
	}
	
	public void printAll(){
		if(stack.isEmpty()){
			System.out.println("Stack is Empty !!");
		}else{
			System.out.print("[");
			for(int i=0; i<stack.size(); i++){
				System.out.print(stack.get(i)+", ");
			}
			System.out.println("]");
		}
	}
	
	
	
	public static void main(String[] args) {
		StackImplement<Integer> st = new StackImplement<Integer>();
		st.push(1);
		st.push(5);
		st.push(2);
		st.printAll();
		
		System.out.println(st.pop()); 
		st.printAll();
		System.out.println(st.pop()); //데이터 삭제 
		st.printAll();
		System.out.println(st.peek()); //데이터 뽑아내기 
		st.printAll();

	}

}

'알고리즘 & 자료구조 > 자료구조-Java' 카테고리의 다른 글

Queue 구현  (0) 2021.07.15
Stack  (0) 2021.07.15
Linked List  (0) 2021.07.14
Single Linked List  (0) 2021.07.14
Double Linked List  (0) 2021.07.14