---
title: "栈内元素排序"
author: "dugu108"
date: "2013-02-16T20:55:25Z"
tags: []
categories: ["行业应用"]
slug: "untitled"
draft: false
lastmod: "2013-02-16T20:55:25Z"
id: 1800424
url: "https://dugu108.iteye.com/blog/1800424"
---

## 分别是利用一个辅助栈和两个辅助栈

```
public class StackSort {
	public static void sortWithOneCache(Stack<Integer> stack) {
		if (stack == null || stack.isEmpty()) {
			return;
		}
		Stack<Integer> cache = new Stack<Integer>();

		while (!stack.isEmpty()) {
			int tmp = stack.pop();
			while (!cache.isEmpty() && tmp < cache.peek()) {
				stack.push(cache.pop());
			}
			cache.push(tmp);
		}

		while (!cache.isEmpty()) {
			stack.push(cache.pop());
		}
	}

	public static void sortWithTwoCache(Stack<Integer> stack) {
		if (stack == null || stack.isEmpty()) {
			return;
		}
		Stack<Integer> cache1 = new Stack<Integer>();
		Stack<Integer> cache2 = new Stack<Integer>();

		while (!stack.isEmpty()) {
			int tmp = stack.pop();
			while (!cache1.isEmpty() && tmp < cache1.peek()) {
				cache2.push(cache1.pop());
			}
			cache1.push(tmp);
			while (!cache2.isEmpty()) {
				cache1.push(cache2.pop());
			}
		}

		while (!cache1.isEmpty()) {
			stack.push(cache1.pop());
		}
	}
}
```