Stack이란
스택은 데이터를 저장하는 추상 자료형 중 하나로, 데이터의 삽입과 삭제가 한쪽 끝에서만 이루어지는 선형 자료 구조이다. 이 때, 데이터를 삽입하는 연산을 "Push", 데이터를 삭제하는 연산을 "Pop"이라고 한다.
스택은 후입선출(LIFO, Last In First Out) 구조를 가지고 있다.
Stack Class
public class Stack {
int size;
int top;
private Integer array[];
public Stack(int size) {
array = new Integer[size];
top=-1;
}
public boolean isEmpty()
{
if (top==-1)
return true;
else return false;
}
public boolean isFull()
{
if (top==array.length-1)
return true;
else return false;
}
void peek(){
System.out.println(array[top]);
}
public int push(int number)
{
if(top<array.length) {
top++;
array[top] = number;
}
return array[top];
}
void pop() {
int temp = array[top];
array[top] = null;
top--;
}
void display()
{
for(int i=0; i < array.length ; i++)
{
System.out.print("["+array[i]+"] ");
}
System.out.println("");
}
}
Stack Main
public class stackMain {
public static void main(String[] args) {
Stack stack = new Stack(3);
stack.display();
stack.push(10);
stack.display();
stack.push(20);
stack.display();
stack.push(30);
stack.display();
stack.peek();
stack.pop();
stack.display();
}
}
'DataStructure' 카테고리의 다른 글
[DataStructure] 큐 (Queue) (1) | 2023.12.04 |
---|