Print a linked list Java

Java Collection, LinkedList Exercises: Display the elements and their positions in a linked list

Last update on December 14 2021 10:51:37 [UTC/GMT +8 hours]

Java Collection, LinkedList Exercises: Exercise-11 with Solution

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

Sample Solution:-

Java Code:

import java.util.LinkedList; import java.util.Iterator; public class Exercise1 { public static void main[String[] args] { // create an empty linked list LinkedList l_list = new LinkedList[]; // use add[] method to add values in the linked list l_list.add["Red"]; l_list.add["Green"]; l_list.add["Black"]; l_list.add["Pink"]; l_list.add["orange"]; // print original list System.out.println["Original linked list:" + l_list]; for[int p=0; p < l_list.size[]; p++] { System.out.println["Element at index "+p+": "+l_list.get[p]]; } } }

Sample Output:

Original linked list:[Red, Green, Black, Pink, orange] Element at index 0: Red Element at index 1: Green Element at index 2: Black Element at index 3: Pink Element at index 4: orange

Pictorial Presentation:


Flowchart:


Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Get the first and last occurrence of the specified elements in a linked list.
Next: Remove a specified element from a linked list.

What is the difficulty level of this exercise?

Easy Medium Hard

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

Java: Tips of the Day

Java: Chunk

Chunks an array into smaller arrays of specified size.

public static int[][] chunk[int[] numbers, int size] { return IntStream.iterate[0, i -> i + size] .limit[[long] Math.ceil[[double] numbers.length / size]] .mapToObj[cur -> Arrays.copyOfRange[numbers, cur, cur + size > numbers.length ? numbers.length : cur + size]] .toArray[int[][]::new]; }

Ref: //bit.ly/36Js4Rq

  • New Content published on w3resource:
  • Scala Programming Exercises, Practice, Solution
  • Python Itertools exercises
  • Python Numpy exercises
  • Python GeoPy Package exercises
  • Python Pandas exercises
  • Python nltk exercises
  • Python BeautifulSoup exercises
  • Form Template
  • Composer - PHP Package Manager
  • PHPUnit - PHP Testing
  • Laravel - PHP Framework
  • Angular - JavaScript Framework
  • Vue - JavaScript Framework
  • Jest - JavaScript Testing Framework

Video liên quan

Chủ Đề