Development/Java

[JAVA] 간단한 스택 구현

@곰팡 2015. 11. 21. 10:19
반응형

스택의 동작




JAVA를 이용한 스택 구현입니다. 
간단하게 배열을 이용한 방법이고, 사용자가 입력하는 size에 따라 Stack의 크기가 결정됩니다. 
크게 어렵지 않으니 활용하시길

스택 클래스에는 기본적으로 Peek, Pop, Push 의 메소드가 구현되어야 기초 동작을 수행할 수 있습니다.

 

package stack;

class Stack {

	int top;
	int[] stack;
	int size;

	public Stack(int size) {
		top = -1;
		stack = new int[size];
		this.size = size;
	}

	public int peek() {
		return stack[top];        
	}

	public void push(int value) {
		stack[++top] = value;
		System.out.println(stack[top] + " PUSH !");
	}

	public int pop() {
		System.out.println(stack[top] + " POP !");
		return stack[top--];
	}

	public void printStack() {
		System.out.println("-- STACK LIST --");
		for (int i = top; i >= 0; i--)
			System.out.println(stack[i]);
		System.out.println("-- END OF LIST --");
	}
}

public class GompangStack {

	public static void main(String args[]) {

               // 스택 동작 테스트
		Stack st = new Stack(100);

		st.push(5);
		st.push(2);
		st.push(3);
		st.push(4);
		st.push(1);

		st.printStack();

		st.pop();

		st.pop();

		st.push(15);

		st.printStack();

		st.peek();
		
		st.pop();
		st.pop();
		st.pop();
		st.pop();
		
		st.push(30);
		
		st.peek();
	}

}

@실행결과


5 PUSH !

2 PUSH !

3 PUSH !

4 PUSH !

1 PUSH !

-- STACK LIST --

1

4

3

2

5

-- END OF LIST --

1 POP !

4 POP !

15 PUSH !

-- STACK LIST --

15

3

2

5

-- END OF LIST --

PEEK : 15

15 POP !

3 POP !

2 POP !

5 POP !

30 PUSH !

PEEK : 30


+ java.util.Stack의 구현체를 열어보자



/**
 * The Stack class represents a last-in-first-out
 * (LIFO) stack of objects. It extends class Vector with five
 * operations that allow a vector to be treated as a stack. The usual
 * push and pop operations are provided, as well as a
 * method to peek at the top item on the stack, a method to test
 * for whether the stack is empty, and a method to search
 * the stack for an item and discover how far it is from the top.
 * When a stack is first created, it contains no items.
 * @author  Jonathan Payne
 * @since   JDK1.0
 */
// java util에서 제공하는 Stack은 Vector를 상속해서 구현한 클래스이다
public class Stack extends Vector {
    /**
     * Creates an empty Stack.
     */
    public Stack() {
    }

    /**
     *  스택의 맨 윗부분에 원소를 집어넣는다. -> Vector의 addElement와 동일한 동작을 한다
     * @param   item   the item to be pushed onto this stack.
     * @return  the item argument.
     * @see     java.util.Vector#addElement
     */
    public E push(E item) {
        addElement(item);

        return item;
    }

    /**
     * top에 있는 요소를 꺼내고 해당 요소를 return 해준다
     *
     * @return  The object at the top of this stack (the last item
     *          of the Vector object).
     * @throws  EmptyStackException  if this stack is empty.
     */
    public synchronized E pop() {
        E       obj;
        int     len = size();

        obj = peek();
        removeElementAt(len - 1);

        return obj;
    }

    /**
     * top에 있는 요소를 제거하지 않고 그냥 조회 용도로 읽어온다
     *
     * @return  the object at the top of this stack (the last item
     *          of the Vector object).
     * @throws  EmptyStackException  if this stack is empty.
     */
    public synchronized E peek() {
        int     len = size();

        if (len == 0)
            throw new EmptyStackException();
        return elementAt(len - 1);
    }

    /**
     * 스택이 비어있는지 확인한다
     * @return  true if and only if this stack contains
     *          no items; false otherwise.
     */
    public boolean empty() {
        return size() == 0;
    }

    /**
     * 스택의 원소를 순회하면서 찾고자 하는 요소가 있는지 확인한다
     * Returns the 1-based position where an object is on this stack.
     * If the object o occurs as an item in this stack, this
     * method returns the distance from the top of the stack of the
     * occurrence nearest the top of the stack; the topmost item on the
     * stack is considered to be at distance 1. The equals
     * method is used to compare o to the
     * items in this stack.
     *
     * @param   o   the desired object.
     * @return  the 1-based position from the top of the stack where
     *          the object is located; the return value -1
     *          indicates that the object is not on the stack.
     */
    public synchronized int search(Object o) {
        int i = lastIndexOf(o);

        if (i >= 0) {
            return size() - i;
        }
        return -1;
    }



반응형