Step-by-step explanation:
We first create a linkedlist named int_list which is empty at the moment.
Next we start adding some integers into the int_list by using addFirst() function. The addFirst() function is different from add() function. The add() function sequencially adds the data into the list whereas addFirst() function always adds the data at the first position.
Next we added few integers into the int_list by using addLast() function. addLast() function always adds the data at the last position of the list.
Lastly, we print the int_list using toString() method which returns the string representation of the list data.
For Example:
Using add() function
int_list.add(1)
output = int_list = [1]
int_list.add(2)
output = int_list = [1, 2]
int_list.add(3)
output = int_list = [1, 2, 3]
Now using addFirst() function
int_list.addFirst(1)
output = int_list = [1]
int_list.addFirst(2)
output = int_list = [2, 1]
int_list.addFirst(3)
output = int_list = [3, 2, 1]
Now using addLast() function
int_list.addLast(4)
output = int_list = [3, 2, 1, 4]
int_list.addLast(5)
output = int_list = [3, 2, 1, 4, 5]
Java Code:
import java.io.*;
import java.util.LinkedList;
public class SinglyLinkedList {
public static void main(String args[]) {
LinkedList int_list = new LinkedList();
// use add() method to add elements in the list
int_list.addFirst(3);
int_list.addFirst(2);
int_list.addFirst(1);
int_list.addFirst(0);
int_list.addLast(4);
int_list.addLast(5);
System.out.println("Here is the list: " + int_list.toString());
}
}
Output:
Here is the list: [0,1,2,3,4,5]