编写程序以升序对堆栈进行排序

编程入门 行业动态 更新时间:2024-10-11 19:18:36
本文介绍了编写程序以升序对堆栈进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有人可以帮忙看看我的代码吗?非常感谢你的帮助.输入堆栈是 [5, 2, 1, 9, 0, 10],我的代码给出了输出堆栈 [0, 9, 1, 2, 5, 10],9 不在正确的位置.

Can someone help look at my code, please? Thank you so much for your help. The input stack is [5, 2, 1, 9, 0, 10], my codes gave output stack [0, 9, 1, 2, 5, 10], 9 is not in the right position.

import java.util.*; public class CC3_6 { public static void main(String[] args) { int[] data = {5, 2, 1, 9, 0, 10}; Stack<Integer> myStack = new Stack<Integer>(); for (int i = 0; i < data.length; i++){ myStack.push(data[i]); } System.out.println(sortStack(myStack)); } public static Stack<Integer> sortStack(Stack<Integer> origin) { if (origin == null) return null; if (origin.size() < 2) return origin; Stack<Integer> result = new Stack<Integer>(); while (!origin.isEmpty()) { int smallest = origin.pop(); int remainder = origin.size(); for (int i = 0; i < remainder; i++) { int element = origin.pop(); if (element < smallest) { origin.push(smallest); smallest = element; } else { origin.push(element); } } result.push(smallest); } return result; }

}

推荐答案

这是我的代码版本,非常简单易懂.

Here's my version of the code which is pretty straightforward to follow.

import java.util.Stack; public class StackSorting { public static void main(String[] args) { Stack<Integer> stack = new Stack<Integer>(); stack.push(12); stack.push(100); stack.push(13); stack.push(50); stack.push(4); System.out.println("Elements on stack before sorting: "+ stack.toString()); stack = sort(stack); System.out.println("Elements on stack after sorting: "+ stack.toString()); } private static Stack<Integer> sort(Stack<Integer> stack) { if (stack.isEmpty()) { return null; } Stack<Integer> sortedStack = new Stack<Integer>(); int element = 0; while(!stack.isEmpty()) { if (stack.peek() <= (element = stack.pop())) { if (sortedStack.isEmpty()) { sortedStack.push(element); } else { while((!sortedStack.isEmpty()) && sortedStack.peek() > element) { stack.push(sortedStack.pop()); } sortedStack.push(element); } } } return sortedStack; } }

更多推荐

编写程序以升序对堆栈进行排序

本文发布于:2023-11-29 05:52:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645524.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:升序   堆栈   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!