Cracking the coding interview--Q3.6

本文介绍了一种使用附加栈对栈进行升序排序的算法,详细解释了实现步骤,并提供了相应的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

原文:

Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write this program: push | pop | peek | isEmpty.

译文:

写一个程序对一个栈进行升序排序,对栈是如何实现的,你不用任何假想,程序能用到的函数有:push,pop,peek,isEmpty

解答

使用一个附加的栈来模拟插入排序。将原栈中的数据依次出栈与附加栈中的栈顶元素比较, 如果附加栈为空,则直接将数据压栈。否则, 如果附加栈的栈顶元素大于从原栈中弹出的元素,则将附加栈的栈顶元素压入原栈。 一直这样查找直到附加栈为空或栈顶元素已经不大于该元素, 则将该元素压入附加栈。这样类似插入排序的方法,之间复杂度为O(n^2)。

代码如下:

import java.util.*;

class Q3_6{

	public static Stack<Integer> sort(Stack<Integer> s) {
		Stack<Integer> r = new Stack<Integer>();
		while(!s.isEmpty()) {
			int tmp = s.pop();
			while(!r.isEmpty() && r.peek() > tmp) {
				s.push(r.pop());
			}
			r.push(tmp);
		}
		return r;
	}
	public static void main(String[] args){
		int[] a={3,6,2,9,7};
		Stack<Integer> s=new Stack<Integer>();
		for(int i=0;i<a.length;i++)
			s.push(a[i]);
		s=sort(s);
		while(!s.isEmpty()){
			System.out.print(s.pop()+" ");
		}
	}
}

---EOF---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值