Sample Problem: Reverse order of items in Java

 Problem:

Given a list of integers in Java, the task is to reverse the given list of integers.

Example:

Input: list[] = {10, 20, 30} Output: 30, 20, 10

Input: list[] = {3, 8, 10, 12, 15} Output: 15, 12, 10, 8, 3

Solution:

There are several ways to reverse a list in Java, including using an auxiliary list to first copy elements and then copy elements in reverse order in the original list, or using two pointers to swap elements. Here, we will use the Stack class from the java.util package to solve this problem.

To reverse a list using a stack:

  1. Traverse the list and push all elements onto the stack, one by one.
  2. Traverse the list again and update the element at the current index with the element at the top of the stack, then pop the stack.

Below is the implementation of this approach:

java
import java.util.*; class Test { static void reverseList(List<Integer> list) { Stack<Integer> stack = new Stack<Integer>(); // Push all elements of the list onto the stack. for (Integer x: list) { stack.push(x); } // Pop the stack and update the list with the popped elements. for (int i = 0; i < list.size(); i++) { list.set(i, stack.pop()); } } public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(10); list.add(20); list.add(30); System.out.println("Original list: " + list); reverseList(list); System.out.println("Reversed list: " + list); } }

Output:

less
Original list: [10, 20, 30] Reversed list: [30, 20, 10]

Time Complexity:

The time complexity of this solution is O(n) if there are n elements in the list.

Auxiliary Space:

The auxiliary space is also O(n), as we need to store all n elements onto a stack to reverse the list.

Note:

This approach is useful when we don't have random access for a particular container, such as linked lists or deque. For arrays, we can use the two-pointer approach described earlier in this article.

Previous Post Next Post