Stack 학습하기

Yuno·2024년 6월 19일

ArrayList를 이용하여 Stack 구현하기

import java.util.ArrayList;

class MyStack1 {
    ArrayList list;

    MyStack1() {
        this.list = new ArrayList();
    }

    public boolean isEmpty() {
        if (this.list.size() == 0) {
            return true;
        } else {
            return false;
        }
    }

    public void push(int data) {
        this.list.add(data);
    }

    public Integer pop() {
        if (this.isEmpty()) {
            System.out.println("Stack is empty");
            return null;
        }
        int data = (int)this.list.get(this.list.size() - 1);
        this.list.remove(this.list.size() - 1);
        return data;
    }

    public Integer peek() {
        if (this.isEmpty()) {
            System.out.println("Stack is empty");
            return null;
        }
        int data = (int)this.list.get(this.list.size() - 1);
        return data;
    }

    public void printStack() {
        System.out.println(this.list);
    }
}

public class Practice1 {
    public static void main(String[] args) {
        // Test code
        MyStack1 myStack = new MyStack1();
        System.out.println(myStack.isEmpty());
        myStack.push(1);
        myStack.push(2);
        myStack.push(3);
        myStack.push(4);
        myStack.push(5);
        myStack.printStack();               // 1, 2, 3, 4, 5

        System.out.println(myStack.peek()); // 5
        myStack.printStack();               // 1, 2, 3, 4, 5

        System.out.println(myStack.pop());  // 5
        System.out.println(myStack.pop());  // 4
        myStack.printStack();               // 1, 2, 3

        System.out.println(myStack.pop());  // 3
        System.out.println(myStack.pop());  // 2
        System.out.println(myStack.pop());  // 1
        myStack.printStack();
    }
}

MyStack1 클래스

-멤버변수

ArrayList list;

ArrayList 를 사용하여 스택의 데이터를 저장하는 리스트. 데이터의 추가와 삭제가 용이하고, 동적으로 크기가 조절되기 때문에 스택에 적합한 자료구조

-생성자

MyStack1() {
	this.list = new ArrayList();

생성자에서는 ArrayList 인스턴스를 생성하여 초기하함. 따라서 MyStack1 객체를 생성하면 내부적으로 빈 리스트가 생성됨

-isEmpty() 메서드

public boolean isEmpty() {
	if (this.list.size() == 0) {
    	return true;
    } else {
    	return false;
    }
}

isEmpty() 메서드는 스택이 비어있는지 확인.
리스트의 크기가 0이면 true를 반환하고, 그렇지 않으면 false

-push(int data) 메서드

public void push(int data) {
	this.list.add(data);
}

push(int data) 메서드는 스택에 데이터를 추가함.
list.add(data) 를 호출하여 데이터의 리스트 맨 끝에 추가

-pop() 메서드

public Integer pop() {
	if (this.isEmpty()) {
    	System.out.println("Stack is empty")
        return null;
    }
    int data = (int)this.list.get(this.list.size() - 1);
	this.list.remove(this.list.size() - 1);
    return data;
}

pop() 메서드는 스택의 맨 위에서 데이터를 제거하고 반환
스택이 비어있으면 메세지를 출력하고 null을 반환
그렇지 않으면 list.get.(this.list.size() - 1)을 통해 리스트의 맨 뒤의 데이터를 가져옴
가져온 데이터를 list.remove(this.list.size() - 1) 를 통해 리스트에서 제거하고 반환

-peek() 메서드

public Integer peek() {
	if (this.isEmpty()) {
    	System.out.prinln("Stack is empty");
        return null;
    }
    int data = (int)this.list.get(this.list.size() - 1);
    return data;

peek() 메서드는 스택의 맨 위에 있는 데이터를 제거하지 않고 반환
스택이 비어있으면 메세지를 출력하고 null을 반환
그렇지 않으면 list.get(this.list.size() - 1)을 통해 리스트의 맨 뒤에 있는 데이터를 가져와서 반환

-printStack() 메서드

public void printStack() {
	System.out.prinln(this.list);
}

printStack 메서드는 현재 스택에 있는 데이터를 출력
출력문을 통해 리스트 전체를 출력

배열을 이용해 기본 Stack 구현하기

class MyStack2 {
    int[] arr;
    int top = -1;

    MyStack2(int size) {
        arr = new int[size];
    }

    public boolean isEmpty() {
        if (this.top == -1) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isFull() {
        if (this.top == this.arr.length - 1) {
            return true;
        } else {
            return false;
        }
    }

    public void push(int data) {
        if (this.isFull()) {
            System.out.println("Stack is full");
            return;
        }
        this.top += 1;
        this.arr[this.top] = data;
    }

    public Integer pop() {
        if (this.isEmpty()) {
            System.out.println("Stack is empty");
            return null;
        }
        int data = this.arr[this.top];
        this.top -= 1;
        return data;
    }

    public Integer peek() {
        if (this.isEmpty()) {
            System.out.println("Stack is empty");
            return null;
        }
        return this.arr[this.top];
    }

    public void printStack() {
        for (int i = 0; i < this.top + 1; i++) {
            System.out.print(this.arr[i] + " ");
        }
        System.out.println();
    }
}

public class Practice2 {
    public static void main(String[] args) {
        // Test code
        MyStack2 myStack = new MyStack2(5);
        System.out.println(myStack.isEmpty());
        myStack.push(1);
        myStack.push(2);
        myStack.push(3);
        myStack.push(4);
        myStack.push(5);
        myStack.push(6);
        myStack.printStack();               // 1, 2, 3, 4, 5

        System.out.println(myStack.peek()); // 5
        myStack.printStack();               // 1, 2, 3, 4, 5

        System.out.println(myStack.pop());  // 5
        System.out.println(myStack.pop());  // 4
        myStack.printStack();               // 1, 2, 3

        System.out.println(myStack.pop());  // 3
        System.out.println(myStack.pop());  // 2
        System.out.println(myStack.pop());  // 1
        myStack.printStack();
    }
}

MyStack2 클래스

-멤버변수

int[] arr;
int top = -1;

arr : 스택의 데이터를 저장할 배열
top : 스택의 가장 위에 있는 데이터의 인덱스를 가리키는 변수. 배열안에 아무것도 없다는 뜻의 -1로 초기화

-생성자

MyStack2(int size) {
	arr = new int[size];
}

생성자에서는 주어진 크기 size의 배열을 생성하여 초기화함. 이 배열을 스택으로 사용

-isEmpty() 메서드

public boolean isEmpty() {
	return (this.top == -1);
}

isEmpty() 메서드는 스택이 비어있는지 여부를 반환
top이 -1이면 스택이 비어있다는 의미이므로 ture를 반환

-isFull() 메서드

public boolean isFull() {
	return (this.top == this.arr.length - 1);
}

isFull() 메서드는 스택이 가득 찼는지 여부를 반환
top이 arr.length - 1과 같으면 스택이 가득 찼다는 의미이므로 true를 반환

-push(int data) 메서드

public void push(int data) {
	if (this.isFull()) {
    System.out.println("Stack is Full");
    return;
    }
    this.top += 1;
    this.arr[this.top] = data;
}

push(int data) 메서드는 스택에 데이터를 추가함.
스택이 가득 찼는지 isFull 메서드로 먼저 확인한 후 가득찼으면 메세지 출력하고 추가하지 않음.
가득 차지 않았으면 top을 증가시키고 this.top 해당위치에 데이터를 저장

-pop() 메서드

public Integer pop() {
	if (this.isEmpty()) {
    	System.out.println("Stack is empty");
        return null;
    }
    int data = this.arr[this.top];
    this.top -= 1;
    return data;
}

pop() 메서드는 스택의 맨 위에 있는 데이터를 제거하고 반환함.
스택이 비어있는지 isEmpty 메서드로 먼저 확인한 후 비어있으면 메세지 출력하고 null을 반환.
비어있지 않으면 top 를 감소시키고 this.top 해당위치에 데이터를 삭제후 반환

-peek() 메서드

public Integer peek() {
	if (this.isEmpty) {
    	System.out.prinln("Stack is empty");
        return null;
    }
    return this.arr[this.top];
}

peek() 메서드는 스택의 맨 위에 있는 데이터를 제거하지 않고 반환
스택이 비어있는지 isEmpty 메서드로 먼저 확인한 후 비어있으면 메세지 출력하고 null을 반환.
비어있지 않으면 top에 있는 데이터를 반환

-printStack() 메서드

public void printStack() {
	for (int i = 0; i < this.top + 1; i++) {
    	System.out.print(this.arr[i] + " ");
    }
    System.out.println();
}
  

printStack 메서드는 현재 스택에 있는 데이터를 출력함
반복문 for문을 사용하여 0부터 top 까지의 인덱스를 순회하면서 각 데이터를 출력함

profile
Hello World

0개의 댓글