shyam97:
私は別のキューを使用して、ソート要素(整数)キュー内に存在しようとしています。。キューが負の数または重複値キューのマストが昇順にソートされていない(頭 - >尾)サンプル入力:4 [7 3 9 5]
出力:[3 5 7 9]
import java.util.*;
public class Source {
public static void main(String args[]) {
Queue<Integer> queue = new LinkedList<Integer>();
Scanner s = new Scanner(System.in);
int n = s.nextInt();
while (n-- > 0)
queue.add(s.nextInt());
sort(queue);
}
// Method to sort the queue
static void sort(Queue<Integer> queue) {
Queue<Integer> queue2 = new LinkedList<Integer>();
queue2.add(queue.remove());
while(queue.size()!=0){
int temp = queue.remove();
queue2.add(temp);
while(temp<queue2.peek()){
queue2.add(queue2.remove());
}
}
System.out.println(queue2);
}
}
NIRF:
あなたは私がやって考えていたキューに負の数を持っていないので、次のように:
1.負の数のインサート最初のキュー(「ダミー」技術)に。
あなたはダミーを打つまで2.最初のキューの最小数を検索します。
ダミーを取り外し3.。
4.手順2で見つかったことを最小値のキューを検索、それを削除し、2番目のキューにそれを挿入します。
最初のキューが空になるまで5これらの4つのステップに従ってください。
Javaコード:
static void sort(Queue<Integer> q1) {
Queue<Integer> q2 = new Queue<Integer>();
int min=Integer.MAX_VALUE;
while (!q1.isEmpty())
{
q1.insert(-1);
while(q1.head() != -1)
{
if (q1.head() < min)
{
min=q1.head();
}
q1.insert(q1.remove());
}
q1.remove(); //removing the -1
while (q1.head() != min)
{
q1.insert(q1.remove());
}
min = Integer.MAX_VALUE;
q2.insert(q1.remove()); //inserting the minimum to the second queue.
}
System.out.println(q2);
}