Title Description
Write a program that sorts the stack in ascending order (that is, the largest element is at the top of the stack), requiring only one additional stack to hold temporary data, but not copying elements into other data structures.
Given a int[] numbers(vector<int> in C + +), where the first element is the top of the stack, return the sorted stack. Note that this is a stack, meaning that you can only access the first element during the sorting process.
Test examples:
[1,2,3,4,5]
return: [5,4,3,2,1]
Import Java.util.stack;import Java.util.arraylist;public class Twostacks {public arraylist<integer> Twostackssort (int[] numbers) {//write code here stack<integer> Stack = new stack<integer> (); stack<integer> stack1 = new stack<integer> (); for (int i=0; i<numbers.length; i++) {Stack.push (numbers[i]);} while (!stack.isempty ()) {int tmp = Stack.pop (). Intvalue (), while (!stack1.isempty () && stack1.peek () > tmp) { Stack.push (Stack1.pop ()); } stack1.push (TMP); } arraylist<integer> tmp1 = new arraylist<integer> (); while (!stack1.isempty ()) {Tmp1.add (Stack1.pop ());} return TMP1; } public stack<integer> TwoStacksSort1 (stack<integer> s) {//write code here stack<integer> St ACK = new stack<integer> (); while (!s.isempty ()) {int tmp = S.pop (), while (!stack.isempty () && stack.peek () > tmp) {s.push (Stack.pop ());} Stack.push (TMP); } return stack; } public static void Main (string[] args) {Twostacks ts = new Twostacks (); int [] numbers = {1,3,2,6,5}; Arraylist<integer> al = Ts.twostackssort (numbers); for (int i=0; i<al.size (); i++) {System.out.print (Al.get (i) + "");}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Dual stack sequencing (Java)