top of page
Click here to go to the home page of AskTheCode.

Problem Solving: Basic List operation using Array in Java | AskTheCode

Team ATC

Updated: Mar 9, 2021

Java program to print a list in reversed order as per liking | Java Programming Solution | Ask The Code

 

Problem:

Did you know that you can also reverse lists and group them according to your liking with proper code?

Let's try it to believe it.


Input Format: The first line contains an odd positive integer. The next lines contains an integer.


Input Sample:

5

1

3

4

5

2


Output Format: A line containing a list.


Output Sample:

[2,5]-[4]-[3,1]


Code:

import java.util.*;

public class Solution_GroupingListRev{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		List<Integer> list1 = new ArrayList<Integer>();
		List<Integer> list2 = new ArrayList<Integer>();
		List<Integer> list3 = new ArrayList<Integer>();

		int a = sc.nextInt();
		int[] arr = new int[a];

		for (int i = 0; i < a; i++) {
			arr[i] = sc.nextInt();
		}

		int bound = a / 2;

		for (int i = a - 1; i >= 0; i--){
			if (i > bound) {
				list1.add(arr[i]);
			}
			else if (i == bound) {
				list2.add(arr[i]);
			}
			else{
				list3.add(arr[i]);
			}
		}
		String m = list1.toString();
		String n = list3.toString();

		m = m.replaceAll("\\s", "");
		n = n.replaceAll("\\s", "");

		System.out.print(m+"-"+list2+"-"+n);
	}
}

Recent Posts

See All

Comments


bottom of page