【发布时间】:2018-11-09 09:28:58
【问题描述】:
输入:输入的第一行包含一个整数 T,表示测试用例的数量。接下来是 T 个测试用例,每个测试用例的第一行包含一个整数 n。第二行由 n 个间隔整数组成。
输出:按相反顺序打印删除中间元素后的栈元素。
输入:1
7
1 2 3 4 5 6 7
输出是:
7 6 5 3 2 1
实际上我可以反向打印,但我不知道如何从堆栈中删除中间元素。请帮助
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args)
{
Scanner s=new Scanner(System.in);
int test=s.nextInt();
for(int t=0;t<test;t++)
{
int n=s.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=s.nextInt();
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<n;i++)
{
stack.push(a[i]);
}
ListIterator<Integer> lstIterator=stack.listIterator(stack.size());
while(lstIterator.hasPrevious())
{
Integer res=lstIterator.previous();
//what condition should i give so that it would print all the
elements except middle one.
System.out.print(res+" ");
}
System.out.println();
}
}
}
【问题讨论】:
-
如果元素个数为偶数,中间元素如何处理?
-
对于这种情况,我将检查 n 是偶数还是奇数,如果是偶数,我将根据测试用例删除 (n/2)-1 位置。例如-n= 6 和元素是 1 2 3 4 5 6 那么我的输出将是 6 5 4 2 1
-
请告诉我删除奇数个元素的中间元素的逻辑