Write a Java program to display the elements and their positions in a linked list


The Java code provided demonstrates how to display elements of a linked list using a for loop and the get method.

  • The code defines a class named Display_Elements with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a LinkedList object named fru_list is created with a type parameter of String, indicating that it will store strings as its elements.
  • Strings such as "Papaya", "Mulberry", "Apple", "Banana", "Cherry", and "Watermelon" are added to fru_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 fru_list before displaying elements.
  • A for loop is used to iterate over the elements of fru_list. The loop variable i represents the index of each element in the list.
  • Inside the loop, the fru_list.get(i) method is called to retrieve the element at index i in fru_list. The retrieved element is then printed using the System.out.println statement, along with the index and a label, resulting in the display of each element and its corresponding index.
  • The output of the program will be the contents of fru_list printed on the first line, followed by each element of fru_list printed on separate lines, along with its corresponding index.

Source Code

import java.util.LinkedList;
import java.util.Iterator;
public class Display_Elements
{
	public static void main(String[] args)
	{
		LinkedList<String> fru_list = new LinkedList<String>();
		fru_list.add("Papaya");
		fru_list.add("Mulberry");
		fru_list.add("Apple");
		fru_list.add("Banana");
		fru_list.add("Cherry");
		fru_list.add("Watermelon");
 
		System.out.println("Original linked list:" + fru_list);  
		for(int i = 0; i < fru_list.size(); i++)
		{
			System.out.println("Element at index "+i+" : "+fru_list.get(i));
		} 
	}
}

Output

Original linked list:[Papaya, Mulberry, Apple, Banana, Cherry, Watermelon]
Element at index 0 : Papaya
Element at index 1 : Mulberry
Element at index 2 : Apple
Element at index 3 : Banana
Element at index 4 : Cherry
Element at index 5 : Watermelon

Example Programs