How to Add Elements in Linked List in Java with the Help of Loop
Here, we are going to add elements like string values in the LinkedList data structure with the Java language. LinkedList is basically managed through C or C++ programming, but here with Java language, the work becomes very much easy for the programmers. The list and the associated links are very easy to manipulate with Java's default methods and classes.
We just have to import the utility package for the LinkedList class. After creating objects of the LinkedList class, we can add elements easily with the add() method.
In this program, we are calling add() method with the help of a For-loop. Taking the nodes number from the user, we can run the loop as much as the user wants to insert elements.
Filename:- MyList.javaimport java.util.*; //importing utility package
import java.util.Scanner; //importing Scanner class for taking input
public class MyList //Main class
import java.util.Scanner; //importing Scanner class for taking input
public class MyList //Main class
{
public static void main(String args[]) //Main method
{
LinkedList<String> ll = new LinkedList<String>(); //Creating object ll of the linked list class
String str; //str for taking strings of linkedlist from user
int i,n;
System.out.println("How many nodes?"); //prompting user to take node numbers
Scanner s=new Scanner(System.in);
n=s.nextInt(); //initializing n with the number of nodes
for(i=0;i<n;i++) //for loop running from 0 to n value
{
System.out.println("Enter the data:"); //prompting user to enter data in the list
Scanner sc=new Scanner(System.in);
str=sc.nextLine(); //initializing str with the user given string value
ll.add(i,str); //adding the string to the list in the i'th position
}
System.out.println(ll); //displaying the list in the ascending value of positions
}
}
public static void main(String args[]) //Main method
{
LinkedList<String> ll = new LinkedList<String>(); //Creating object ll of the linked list class
String str; //str for taking strings of linkedlist from user
int i,n;
System.out.println("How many nodes?"); //prompting user to take node numbers
Scanner s=new Scanner(System.in);
n=s.nextInt(); //initializing n with the number of nodes
for(i=0;i<n;i++) //for loop running from 0 to n value
{
System.out.println("Enter the data:"); //prompting user to enter data in the list
Scanner sc=new Scanner(System.in);
str=sc.nextLine(); //initializing str with the user given string value
ll.add(i,str); //adding the string to the list in the i'th position
}
System.out.println(ll); //displaying the list in the ascending value of positions
}
}
Output:-
0 Comments