這種反向隊列中的數字是一個評價的問題(不要求HW的答案!)在奇數指標
編寫逆轉整數的隊列中的元素的一半順序的方法reverseHalf。假設隊列中的第一個值具有位置0,那麼您的方法應該顛倒奇數位置(位置1,3,5等)中所有元素的順序。例如,如果隊列最初存儲了這個數字序列當調用該方法時:
index:0 1 2 3 4 5 6 7 front [1,8,7,2,9,18,12,0] back - 它應該存儲以下值方法結束執行:
index:0 1 2 3 4 5 6 7 front [1,0,7,18,9,2,12,8]返回 請注意,偶數位置(位置0,2 ,4,6)沒有移動。該數字的子序列仍然是:(1,7,9,12)。但請注意,奇數位置(位置1,3,5,7)的數字現在與原始數據相反。換句話說,原始的子序列:(8,2,18,0)已變爲:(0,18,2,8)。您可以使用單個堆棧作爲輔助存儲。
我已經得到它與我的隊列中的偶數個元素一起工作,但當涉及到一個奇數時我就失去了......我是否必須重新構造我的整個程序?或者這是一個快速修復?
我的代碼:
public static void reverseHalf(Queue<Integer> q){
int size = q.size();
Stack<Integer> s = new Stack<Integer>();
for(int i = 0; i < size; i++){
int n = q.remove();
s.push(n);
q.add(n);
}
for(int i = 0; i < size; i++){
int n = q.remove();
if(i % 2 == 0){
q.add(n);
}
}
for(int i = 0; i < size; i++){
int n = s.pop();
if(i % 2 == 0)
q.add(n);
}
for(int i = 0; i < size; i++){
int n = q.remove();
s.push(n);
q.add(n);
}
for(int i = (size/2); i < size; i++){
q.remove();
}
for(int i = 0; i < (size/2); i++){
s.pop();
}
for(int i = 0; i < size/2; i++){
q.add(s.pop());
}
s.clear();
for(int i = 0; i < size; i++){
int n = q.remove();
s.push(n);
q.add(n);
}
for(int i = 0; i < (size/2); i++){
int n = s.pop();
int m = q.remove();
q.add(n);
q.add(m);
}
for(int i = 0; i < (size/2); i++){
q.remove();
}
}