반응형
Stack(스택)- 영어적으로 해석하면 "쌓다"라는 의미를 가지고 있다.
Stack 기본 개념
- LIFO(Last In First Out)이라고 먼저 들어가면 제일 늦게 나온다 라는 말이다.
- 한쪽으로만 데이터를 넣고 뺄 수 있다.
- 구조상 직전의 넣은 데이터를 빠르게 가져올 수 있다.
- 비어있는 스택에서 원소를 추출하려고 할 때 stack underflow라고 한다.
- 스택이 넘치는 경우 stack overflow라고 한다.
주요 메서드
함수 | 설명 |
push() | 값을 추가하는 기능 |
pop() | 맨위에 있는 값을 제거하는 기능 |
isEmpty() | 공간이 비워져있는지 체크 하는 기능 |
peek() | 맨 위에 있는 값을 반환 하는 기능 |
public class ex01 {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();// 선언 하는 방법
stack.push(1);// 추가하기
stack.push(2);
stack.push(3);
stack.push(4);
stack.pop();// 맨위 값을 제거
stack.pop();
System.out.println(stack);// 스택 에 있는 값을 출력하기
System.out.println(stack.isEmpty());// 비워져있는지 체크 결과값 boolean 으로 반환
stack.pop();
stack.pop();
System.out.println(stack.isEmpty());
stack.push(1);
System.out.println(stack.peek());//맨위 에 있는 값을 출력
한번 따라 해 보셰요 그래야 어떻게 이런 기능들이 작동하는지 조금 더 쉽게 이해할 수 있습니다.
public class Example02 {
public static void main(String[] args) {
//배열을 스택 만들기
//생성자는 public
Scanner sc= new Scanner(System.in);
int n = sc.nextInt();// 최대 값 즉배열의 사이즈 n 이다
ArrayStack stack = new ArrayStack(n);
while (true){
System.out.println("1.push 2.pop 3.peek 4.clear 5.print 0.exit : ");
int num= sc.nextInt();
if (num ==0) break;
int x;
switch (num){
case 1:
int m = sc.nextInt();
x = stack.push(m);
System.out.println(x);
break;
case 2:
x = stack.pop();
System.out.println(x);
break;
case 3:
x = stack.peek();
System.out.println(x);
break;
case 4:
stack.clear();
break;
case 5:
stack.print();
break;
default:
}
}
}
}
class ArrayStack{
private int top;
private int capacity;
private int stack[];// object를 사용해서 문자 정수 불린 다 받을수 있다
public ArrayStack(int n){
this.top =-1;
this.capacity =n;
stack = new int[n];
}
public int push(int x){
if(isFull()){
System.out.println("스택is full ");
return -1;
}else {
stack[++top] = x;// 전위증가 top의 위치를먼저 변경 시키고 값을 대입
}
return x;
}
public int pop(){
if(isEmpty()){
System.out.println("stack is empty");
return -1;
}else {
// top을 값을 계산하고 나서
// int x = stack[top];
// stack[top--] =0;
// return x;
return stack[top--];
}
}
public int peek(){
if(isEmpty()){
System.out.println("stack is empty");
return -1;
}else {
return stack[top];
}
}
public void clear(){
this.top = -1;
//
// Arrays.fill(this.stack,0);
this.stack =new int[this.capacity];
}
public boolean isFull(){
return this.top >= this.capacity -1;
}
public boolean isEmpty(){
return this.top ==-1;
}
public int size(){
return this.top+1;
}
public void print(){
if(isEmpty()){
System.out.println("stack is empty");
}
else {
System.out.println(Arrays.toString(stack));
}
}
}
반응형
'자료구조' 카테고리의 다른 글
버블 정렬(bubbleSort) (0) | 2024.08.27 |
---|---|
Queue(큐) (0) | 2024.08.17 |
CollectionFrameWork - ArrayList, Linked list (0) | 2024.08.05 |
배열(Array) (0) | 2024.07.22 |