package Datastructure;
import java.util.Stack;
/*
* empty();-- 스택이 비어있는지 검사
* peek(); 스택 맨위의 객체 리턴
* pop(); 스택 맨위 객체 삭제
* push(); 새객체를 스택 맨위에 삽입
* search(); 원하는 객체의 위치를 리턴
*
*/
public class Stackpracticearray {
int top=0;
Object stack[];
int size=0;
public Stackpracticearray(int size){
stack = new Object [size];
this.size=size;
}
public boolean empty(){
if(top==-1 ){
return true;
}
else{
return false;
}
}
public Object peek(){
System.out.println(stack[this.top-1]);
return stack[this.top];
}
public void pop(){
if(top<0){
System.out.println("error");
}
else{
top--;
stack[top]=0;
}
}
public void push(Object input){
if(top> size-1){
System.out.println("error");
}
else{
//top++;
stack[top++]=input;// top -1로 두면 아웃오브 인덱스 뜸 이렇게 하고 -1 을 하면 -1에는 아무것도 없고 0에서 부터 채워서 그런듯?
}
}
public int search(Object search){
Object s=null;
for(int i=0; i<top;i++){
s=stack[i];
if(s == search)
{
search=s;
}
}
return (Integer) search;
}
public void see(){
Object s=null;
for(int i=0; i<top;i++){
s=stack[i];
System.out.println(s);
}
}
public static void main(String[] args) {
Stackpracticearray s = new Stackpracticearray(6);
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
//s.push(7);
s.pop();
s.pop();
s.see();
s.peek(); // -1 을 위해서 안해주니깐 다음인덱스가 나왔다
//System.out.println(s.stack[3]);
/*int a=s.search(3);
System.out.println(3);*/
//System.out.println(s.peek());
}
}
※ 주의
수도코드에서는 스택의 최근 데이터 위치를 가르키는 top 이 0 인경우 데이터가 없다는 것으로 간주 합니다.
하지만 실제 소스코드 작성시 배열을 사용한다면 배열의 시작은 0 이기 때문에
top 을 -1 로 초기화 해야 합므로 주의 하세요!
http://globalbiz.tistory.com/78
'자료구조' 카테고리의 다른 글
배열 기반의 힙 , 우선순위 큐 구현 하기 (0) | 2015.05.31 |
---|---|
우선순위 큐 정리 (0) | 2015.05.31 |
힙 정리 (0) | 2015.05.30 |
큐 정리 소스 포함 (0) | 2015.05.30 |
링크드 리스트 전체 소스 (0) | 2015.05.29 |