使用另一个堆栈对堆栈进行排序
如果您想练习数据结构和算法程序,可以通过 100多种数据结构和算法程序.
在这篇文章中,我们将看到如何使用另一个堆栈对堆栈进行排序。
问题
给定堆栈,您需要在临时的帮助下对其进行排序 叠.
解决方案:
- 让’s say, you have two 叠s,
叠
and临时堆栈
. - Pop an element
currentData
from叠
and compare it with head of临时堆栈
. - If
currentData
it greater, 推 it to临时堆栈
. - If
currentData
is lesser than head of临时堆栈
, 流行音乐 an element from临时堆栈
and 推 it to叠
until you get the element which is greater thancurrentData
- In the end,
临时堆栈
will be sorted 叠.
爪哇代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
上市 静态的 StackCustom sortStack(StackCustom 叠) { StackCustom 临时堆栈 = 新 StackCustom(10); 而(!叠.是空的()) { 整型 currentData=叠.流行音乐(); 而(!临时堆栈.是空的() && 临时堆栈.窥视() > currentData) { 叠.推(临时堆栈.流行音乐()); } 临时堆栈.推(currentData); } 返回 临时堆栈; } |
使用附加堆栈对堆栈进行排序的完整Java程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
包 组织.Arpit.爪哇2blog; / ** * @作者Arpit Mandliya * / 上市 类 StackCustom { 整型 尺寸; 整型 rr[]; 整型 最佳; StackCustom(整型 尺寸) { 这个.尺寸 = 尺寸; 这个.rr = 新 整型[尺寸]; 这个.最佳 = -1; } 上市 虚空 推(整型 推Element) { 如果 (!已满()) { 最佳++; rr[最佳] = 推Element; } 其他 { 系统.出.打印(“堆栈已满!”); } } 上市 整型 流行音乐() { 如果 (!是空的()) { 整型 返回顶部 = 最佳; 最佳-; 返回 rr[返回顶部]; } 其他 { 系统.出.打印(“堆栈是空的!”); 返回 -1; } } 上市 整型 窥视() { 返回 rr[最佳]; } 上市 布尔值 是空的() { 返回 (最佳 == -1); } 上市 布尔值 已满() { 返回 (尺寸 - 1 == 最佳); } 上市 静态的 虚空 主要(串[] args) { StackCustom 叠Custom = 新 StackCustom(10); 系统.出.打印(“ == ===============”); 叠Custom.推(10); 叠Custom.推(30); 叠Custom.推(50); 叠Custom.推(40); 叠Custom.printStack(叠Custom); StackCustom sortedStack=sortStack(叠Custom); 系统.出.打印(“ == ===============”); 系统.出.打印(“排序后:”); 系统.出.打印(“ == ===============”); sortedStack.printStack(sortedStack); } //使用另一个堆栈对堆栈进行排序 上市 静态的 StackCustom sortStack(StackCustom 叠) { StackCustom 临时堆栈 = 新 StackCustom(10); 而(!叠.是空的()) { 整型 currentData=叠.流行音乐(); 而(!临时堆栈.是空的() && 临时堆栈.窥视() > currentData) { 叠.推(临时堆栈.流行音乐()); } 临时堆栈.推(currentData); } 返回 临时堆栈; } 上市 虚空 printStack(StackCustom 叠) { 如果(最佳>=0) { 系统.出.打印(“堆栈的元素是:”); 对于 (整型 i = 0; i <= 最佳; i++) { 系统.出.打印(rr[i]); } } } } |
当您在程序上方运行时,将获得以下输出
堆栈的元素是:
10
30
50
40
== == =============
排序后:
== == =============
堆栈的元素是:
10
30
40
50
那’关于如何使用另一个堆栈对堆栈进行排序的所有内容