Use one stack to implement the sorting of another stack

Problem Description

    The type of the elements in a stack is an integer. Now, if you want to sort the stack from the top to the bottom in descending order, you can only apply for one stack. In addition, new variables can be requested, but no additional data structures can be requested. 

answer

    The stack to be sorted is recorded as stack, the applied auxiliary stack is recorded as help, the pop operation is performed on the stack, and the popped element is recorded as cur.

  •     If cur is less than or equal to the top element of help, push cur directly into help;
  •     If cur is greater than the top element of help, pop the elements of help one by one and push them into the stack one by one until cur is less than or equal to the top element of help, and then push cur into help.

    The above operations are performed until all elements in the stack are pushed into help. Finally, push the elements in help into the stack one by one to complete the sorting.

public static void sortStackByStack(Stack<Integer> stack) {
	 Stack<Integer> help = new Stack<Integer>();
	 while(!stack.isEmpty()) {
		 int cur = stack.pop();
		 while(!help.isEmpty()&&help.peek()>cur) {
			 stack.push(help.pop());
		 }
		 help.push(cur);
	 }
	 while(help.isEmpty()) {
		 stack.push(help.pop());
	 }
 }


Guess you like

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