Backend/Java
원본 글 보기

[Java] 자료구조: 스택(Stack) 구현하기

자바로 스택 짜보기

스택 설명

스택은 대충 이런 거였어요

[문제의 코드]



public class Stack{
	int[] st=new int[5];
	int top = -1;
public void push(int num) {
		top++;
		st[top]=num;
}
public void pop() {
		st[top]=0;
		top--;
}
public static void main(String[] args) {		
		Stack s = new Stack();
		s.push(10);
		s.push(20);
		s.push(30);
for (int i=0; i<s.st.length; i++) {
			System.out.println(s.st[i]);
}
		
		s.pop();
for (int i=0; i<s.st.length; i++) {
			System.out.println(s.st[i]);
}
		
		s.pop();
for (int i=0; i<s.st.length; i++) {
			System.out.println(s.st[i]);
}
}
}


이렇게 했을 때의 문제 !!

1. s.st.length 이렇게 접근해서

- print 했을 때 0이 나옴: 유효하지 않은 데이터가 나옴.

2. 객체지향 원리에 어긋남(캡슐화) : Stack과 client 사이 결합도가 높아짐.

stack 코드가 바뀌면 client 도 다 바꿔줘야하는 문제 발생.

[ 고친코드 ]

Stack.java



public class Stack {
private int[] st = new int[5];
private int top = -1;
private int length = 0;
public void push(int num) {
		top++;
		st[top] = num;
		length++;
// st[++top]=num; <-이렇게 하는게 더 깔끔하지만 뭐..
}
public void pop() {
		st[top] = 0;
		top--;
		length--;
// st[top--] = 0;
}
public int peek() {
return st[top];
}
public boolean isEmpty() {
return top == -1;
}
}


StackClient.java




public class StackClient {
public static void main(String[] args) {		
		Stack s = new Stack();
		s.push(10);
		s.push(20);
		s.push(30);
while (s.isEmpty()==false) {
			System.out.println(s.peek());
			s.pop();
}
}
}