Write a Java program to shuffle the elements in a linked list


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

  • The code defines a class named Shuffle_Element 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 shuffling the elements.
  • The Collections.shuffle method is called with col_list as the argument. This method shuffles the elements in the linked list randomly.
  • The System.out.println statement is used to print the contents of col_list after shuffling the elements. As a result, the linked list with shuffled elements will be printed.
  • The output of the program will be the contents of col_list printed before and after shuffling the elements.

Source Code

import java.util.*;
public class Shuffle_Element
{
	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("Before Shuffling Linked list : " + col_list);  
		Collections.shuffle(col_list);
		System.out.println("After Shuffling Linked list : " + col_list); 
	}
}

Output

Before Shuffling Linked list : [Blue, Green, Pink, Black, Red, orange]
After Shuffling Linked list : [Red, orange, Pink, Blue, Green, Black]

Example Programs