用一个栈实现对另一个栈的排序
2021-06-22 20:08
阅读:543
标签:sort port des imp http poe class 整型 比较
题目
一个栈的元素为整型,现在想将该栈的从栈顶到底按从小到大的顺序排序,只许申请一个栈。除此之外,可以申请新变量,但不能申请额外的数据结构。
难度 ?
思路
- 选择一个stack.pop()弹出的栈(旧栈)顶元素作为比较值,装入到一个新的栈中
- 用新栈的栈顶值比较旧栈再弹出的值
- 如果新栈的值大于旧栈的值,则将旧栈的值装入到新栈中
-
如果新栈的值小于旧栈的值,则将新栈的值弹出装入到旧栈中
Stack
help = new Stack (); while(!stack.isEmpty()){ int cur = stack.pop(); while(!help.isEmpty() && help.peek() 流程一
流程二 当新栈不为空时,将新栈的值全部弹出,再装入旧栈中
while (!help.isEmpty()){ stack.push(help.pop()); }
看完上面的图,到这已经很好理解了,没必要在画图了...
实现
package com.test.desc;
import org.junit.Test;
import java.util.Stack;
/**
* @author lorem
* @date 2018.9.11
*/
public class TestStackDesc {
@Test
public void test(){
Stack stack = new Stack();
stack.push(1);
stack.push(3);
stack.push(2);
sortStackByStack(stack);
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
}
public void sortStackByStack(Stack stack) {
Stack help = new Stack();
while(!stack.isEmpty()){
int cur = stack.pop();
while(!help.isEmpty() && help.peek()
用一个栈实现对另一个栈的排序
标签:sort port des imp http poe class 整型 比较
原文地址:https://www.cnblogs.com/loremwalker/p/9676666.html
评论
亲,登录后才可以留言!