Write a Java program of swap two elements in a linked list


The Java code provided demonstrates how to swap two elements in a linked list using the Collections.swap method.

  • The code defines a class named SwapTwo_Elements with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a LinkedList object named col_list is created with a type parameter of String, indicating that it will store strings as its elements.
  • Strings such as "Blue", "Green", "Pink", "Black", "Red", and "Orange" are added to col_list using the add method, which appends the elements to the end of the list.
  • The System.out.println statement is used to print the contents of col_list before swapping the elements.
  • The Collections.swap method is called with col_list as the first argument, and the indices of the two elements to be swapped, 1 and 5, as the second and third arguments respectively. This method swaps the elements at the specified indices in the linked list.
  • The System.out.println statement is used to print the contents of col_list after swapping the elements. As a result, the linked list with the elements swapped will be printed.
  • The output of the program will be the contents of col_list printed before and after swapping the elements.

Source Code

import java.util.*;
public class SwapTwo_Elements
{
	public static void main(String[] args)
	{
		LinkedList <String> col_list = new LinkedList <String> ();
		col_list.add("Blue");
		col_list.add("Green");
		col_list.add("Pink");
		col_list.add("Black");
		col_list.add("Red");
		col_list.add("orange");
		System.out.println("The Given linked list : " + col_list);
		Collections.swap(col_list, 1, 5);
		System.out.println("After Swap Two Elements in a Linked List : " + col_list);
	}
}

Output

The Given linked list : [Blue, Green, Pink, Black, Red, orange]
After Swap Two Elements in a Linked List : [Blue, orange, Pink, Black, Red, Green]

Example Programs