How to reverse a stack using only recursive functions and stack operations (JAVA)

Problem Description:

        A stack is pushed into 1, 2, 3, 4, 5 in sequence, that is, 5, 4, 3, 2, 1 from the top of the stack to the bottom of the stack. After transposing the stack, it is 1, 2, 3, 4, and 5 from the top of the stack to the bottom of the stack, that is, the reverse order of the stack is completed. It can only be implemented with recursive functions, no other data structures can be used.

answer:

Recursive function 1: Return and remove the bottom element of the stack stack. code show as below:

public static int getAndRemoveLastElement(Stack<Integer> stack) {
	  int result = stack.pop();
	  if(stack.isEmpty()) {
		   return result;
	  }else {
		  int last = getAndRemoveLastElement(stack);
		  stack.push(result);
		  return last;
	  }
  }

Recursive function 2: Reverse a stack, which is the method required by the title. The specific process is as follows: the reserve method in the code. This method calls recursive function one.

public static void reverse(Stack<Integer> stack) {
	  if(stack.isEmpty()) {
		  return;
	  }
	  int i = getAndRemoveLastElement(stack);
	  reverse(stack);
	  stack.push(i);
  }




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324711481&siteId=291194637
Recommended