본문 바로가기

JAVA

Stack 구현

public class Ex76_Stack {


public static void main(String[] args) {

// Ex76_Stack.java

//구현할것

//1. void push(String value)

//2. int size()

//3. String pop()

//4. String peek()

//5. clear()

//6. 배열의 길이를 가변으로 구현(스택객체 생성 직후는 배열이 없음-> 첫add()호출 시 4칸 짜리 생성->데이터가 꽉차면 2배로 방생성)

//7. void trimTosize()


//배열 생성

MyStack stack = new MyStack();


//추가

stack.push("빨강");

stack.push("노랑");

stack.push("파랑");

stack.push("주황");

stack.push("검정");

//읽기

System.out.println(stack.pop());

System.out.println(stack.pop());

System.out.println(stack.pop());

//개수

System.out.println(stack.size());

//확인

System.out.println(stack.peek());

System.out.println(stack.peek());

System.out.println(stack.size());

// //크기 조절

// stack.trimToSize();

//

//초기화

stack.clear();

System.out.println(stack.size());


}


}



class MyStack{

private int index;

private String[] list;

public MyStack() {

this.index =-1;

this.list = new String[4];

}

public void push(String value) {

this.index++;

if(this.index ==list.length) {

String[] temp = new String[list.length*2];

for(int i=0;i<list.length;i++) {

temp[i] = list[i];

}

this.list =new String[temp.length];

for(int i=0;i<list.length;i++) {

list[i] = temp[i];

}

}

list[this.index] = value;

//현재 this.index = 3;

}

public String pop() {

String value = list[this.index];

this.index--;

return value;

}

public int size() {

return this.index+1;

}

public String peek() {

return list[this.index];

}

public void clear() {

for(int i=list.length-1;i>=0;i--) {

list[i]=null;

}

this.index =-1;

}

public void trimToSize() {

String[] temp = new String[this.index+1]; 

for(int i=0;i<temp.length;i++) { 

temp[i] = this.list[i]; 

this.list = temp;

}


}


///////////////결과값/////////////////

검정 //System.out.println(stack.pop());

주황 //System.out.println(stack.pop());
파랑 //System.out.println(stack.pop());

//System.out.println(stack.size());

//확인
노랑 //System.out.println(stack.peek());
노랑 //System.out.println(stack.peek());
//System.out.println(stack.size());

//초기화


'JAVA' 카테고리의 다른 글

1.파일 입출력(Data)  (0) 2018.08.02
File.io  (0) 2018.08.01
Queue 구현  (0) 2018.07.31
Stack(스택,큐)  (0) 2018.07.31
ArrayList 구현  (0) 2018.07.31