[英]printing the elements by removing middle element of stack
輸入:輸入的第一行包含一個整數 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();
}
}
}
您可以使用pop()
方法彈出返回並刪除堆棧的頂部元素,這樣您就可以以相反的順序創建和填充新堆棧,不需要反轉迭代器,看看代碼以下。
import java.util.ListIterator;
import java.util.Scanner;
import java.util.Stack;
class GFG {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
//Define stacks here
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> new_stack = new Stack<Integer>();
int test = s.nextInt();
for (int t = 0; t < test; t++) {
int n = s.nextInt();
int a[] = new int[n];
double middle = Math.ceil((double) n / 2);
System.out.println("Middle is : " + middle);
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
// add elements to stack
for (int i = 0; i < n; i++) {
stack.push(a[i]);
}
//popping the elements of stack
for (int j = 0; j < n; j++) {
Integer element = stack.pop();
if (j != middle -1) {
new_stack.push(element);
}
}
ListIterator<Integer> lstIterator = new_stack.listIterator(stack.size());
while (lstIterator.hasNext()) {
Integer res = lstIterator.next();
//what condition should i give so that it would print all the elements except middle one.
System.out.print(res + " ");
}
System.out.println();
}
}
}
不要插入輸入數組的中間元素。
獲取中間元素索引:
int middle = a.length/2;
不要將中間元素壓入堆棧:
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<n;i++){
if(i != middle)
stack.push(a[i]);
}
其他一切看起來都不錯。 只需確保為變量提供有意義的名稱。
您可以簡單地使用遞歸來刪除堆棧的中間元素。
當前 = 0
mid = stack.size()/2
static void delete(Stack<Integer> stack, int current, int mid){ if(stack.isEmpty()) return; if(current == mid){ stack.pop(); return; } int x = stack.pop(); current++; delete(stack, current, mid); stack.push(x); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.