Topic 1: Use a secondary stack and some additional non-array variables to store the elements in the stack s in ascending order.
Topic 2: Use a secondary queue and some additional non-array variables to store the elements in queue Q in ascending order.
1. Java implementation, the first use of linked list LinkedList structure stack data structure.
import java.util.LinkedList;
public class IntStack {
private LinkedList<Integer> storage = new LinkedList<Integer> ();
/** 入栈 */
public void push(int v) {
storage.addFirst(v);
}
/** 出栈,但不删除 */
public int peek() {
return storage.getFirst();
}
/** 出栈 */
public int pop() {
return storage.removeFirst();
}
/** 栈是否为空 */
public boolean empty() {
return storage.isEmpty();
}
/** 打印栈元素 */
public String toString() {
return storage.toString();
}
}
2. Use two stacks for sorting operations.
2.1 Method Init (int[] ints, IntStack stack) deposit data into stack 1;
2.2 Method Sort (), the main algorithm is:
[1]sizeone and Sizetwo record the number of data to be sorted in the current two stacks;
[2] do the loop until the number of data to be sorted in a stack is 1, which indicates that the order is complete;
[3] The process of sorting is,
[3.1] First out of the stack 1 from the unsorted data, find the largest, stored in Max, and the rest into the stack 2;
[3.2] At this time the largest person of the data was found;
[3.3] Again, from the stack 2 in order to take out the unsorted data, find the largest, deposit max, and the rest into the stack 1;
[3.4] At this time already found the second largest of the data;
[3.5] alternating and reciprocating sequentially until the termination condition is satisfied [2];
[3.6] At this time Sizeone and Sizetow of the inevitable one is 0, one is 1;