2008년 7월 22일 화요일

java Stack recursion

자바 스택출력 재귀호출 관련 소스


public class StackTest {

public static void main( String[] args ) {

Stack stack = new Stack(6);
Stack stack2 = new Stack(6);

stack.push( '2' );
stack.push( '6' );
stack.push( '3' );
stack.push( '7' );
stack.push( '1' );
stack.push( '9' );

System.out.print("First array elements are: ");
stack.print();

System.out.print("\n");
System.out.print("Second array elements are: ");

//char s;
//do {
//
//s = stack.pop();
//stack2.push(s);
//
//}while ( s!=('2') );


recursion_F(stack,stack2);

stack2.print();
}

private static void recursion_F(Stack stack, Stack stack2) {
// TODO Auto-generated method stub
char s;
s = stack.pop();
stack2.push(s);
if( s==('2')) return;
recursion_F(stack,stack2);
// 자기자신을 재귀호출(recursion)부분
}

}

class Stack {

private int maxSize;

private char[] stackArray;

private int top;

public Stack(int s) {

maxSize = s;

stackArray = new char[maxSize];

top = -1;

}

public void print() {

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

System.out.print(stackArray [i] +" ");

}

}

public void push(char j) {

stackArray[++top] = j;

}

public char pop() {

return stackArray[top--];

}

public char peek() {

return stackArray[top];

}

public boolean isEmpty() {

return (top == -1);

}

public boolean isFull() {

return (top == maxSize - 1);

}
}


문]

'StackTest' 클래스안의 do, while 구문을 재귀호출(recursion)로 바꾸어서똑같이 출력하고 싶습니다.

댓글 없음:

댓글 쓰기

-


Sidewinder


World


FishMusic


LaughingBaby