有人可以帮忙看看我的代码吗?非常感谢你的帮助.
输入堆栈为[5、2、1、9、0、10],我的代码给出了输出堆栈[0、9、1、2、5、10],9不在正确的位置.
import java.util.*;
public class CC3_6 {
public static void main(String[] args) {
int[] data = {5, 2, 1, 9, 0, 10};
Stack myStack = new Stack();
for (int i = 0; i < data.length; i++){
myStack.push(data[i]);
}
System.out.println(sortStack(myStack));
}
public static Stack sortStack(Stack origin) {
if (origin == null)
return null;
if (origin.size() < 2)
return origin;
Stack result = new Stack();
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;
}
}
最佳答案
/** the basic idea is we go on popping one one element from the original
* stack (s) and we compare it with the new stack (temp) if the popped
* element from original stack is < the peek element from new stack temp
* than we push the new stack element to original stack and recursively keep
* calling till temp is not empty and than push the element at the right
* place. else we push the element to the new stack temp if original element
* popped is > than new temp stack. Entire logic is recursive.
*/
public void sortstk( Stack s )
{
Stack temp = new Stack();
while( !s.isEmpty() )
{
int s1 = (int) s.pop();
while( !temp.isEmpty() && (temp.peek() > s1) )
{
s.push( temp.pop() );
}
temp.push( s1 );
}
// Print the entire sorted stack from temp stack
for( int i = 0; i < temp.size(); i++ )
{
System.out.println( temp.elementAt( i ) );
}
}