-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsteroids.java
More file actions
50 lines (49 loc) · 1.52 KB
/
Asteroids.java
File metadata and controls
50 lines (49 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.*;
public class Asteroids{
public static void state(int arr[]){
Stack<Integer> s = new Stack<>();
for(int i=0;i<arr.length;i++){
if (s.isEmpty()){
s.push(arr[i]);
}else if(s.peek()>0 && arr[i]>0){
s.push(arr[i]);
}else{
boolean con=true;
while(!s.isEmpty() && s.peek()>0 && arr[i]<0 ){
if (s.peek()==Math.abs(arr[i])){
s.pop();
con=false;
break;
}else if(s.peek()<Math.abs(arr[i])){
s.pop();
}else if(s.peek()>Math.abs(arr[i])){
con=false;
break;
}
}
if (con){
s.push(arr[i]);
}
}
}
int arr1[]=new int[s.size()];
for(int i=s.size()-1;i>=0;i--){
arr1[i]=s.peek();
s.pop();
}
for(int i=0;i<arr1.length;i++){
System.out.print(arr1[i]+" ");
}System.out.println();
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter size: ");
int size = sc.nextInt();
int arr[] = new int[size];
System.out.println("Enter " + size + " elements:");
for(int i = 0; i < size; i++){
arr[i] = sc.nextInt();
}
state(arr);
}
}