-
[whiteship스터디 4주차 과제]배열을 이용한 스택 구현CS/자료구조 2021. 5. 15. 09:40
Stack 클래스
package Week3_Stack; public class Stack { private int[] list; private int pointer; private int size; Stack(int size) { this.pointer = 0; this.size = size; this.list = new int[size]; } void push(int data) { if (pointer >= size) { System.out.println("OverFlow"); return; } list[pointer] = data; pointer++; //스택의 상태를 출력 for (int i = 0; i < pointer; i++) { System.out.print(list[i] + " -> "); } System.out.println(); } int pop() { if (pointer <= 0) { System.out.println("Out of index"); return -1; } pointer--; return list[pointer]; } }
package Week3_Stack; public class StackTest { public static void main(String[] args) { Stack stack = new Stack(5); stack.push(1); stack.push(2); stack.push(3); stack.push(4); stack.push(5); //overflow push stack.push(6); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); //empty System.out.println(stack.pop()); } }
[결과]
'CS > 자료구조' 카테고리의 다른 글
Swift에서 힙, 우선순위 큐 사용하기 (100% 순수 구현을 곁들인) (0) 2024.07.30 [whiteship스터디 4주차 과제]LinkedList를 이용해 Queue 구현 (0) 2021.06.19 [whiteship스터디 4주차 과제]ListNode클래스를 이용해 Stack구현 (0) 2021.05.16 [whiteship스터디]single linked list 구현 (0) 2021.04.11