Mark As Completed Discussion

Creating a Linked List

To create a linked list, we first need to define the Node class, which represents an element in the list. Each Node object contains a data field to store the value of the element and a next field to point to the next element in the list.

In Java, the Node class can be defined as follows:

TEXT/X-JAVA
1class Node {
2    int data;
3    Node next;
4
5    public Node(int data) {
6        this.data = data;
7        this.next = null;
8    }
9}

Once the Node class is defined, we can create the LinkedList class to manage the linked list. The LinkedList class has a head field to point to the first element in the list.

To create a new linked list, we can initialize the head to null, indicating an empty list.

TEXT/X-JAVA
1LinkedList ll = new LinkedList();

To add elements to the linked list, we create a new Node object with the desired value and set its next field to null. If the list is empty, we set the head to the new node. Otherwise, we traverse the list until we reach the last node and set its next field to the new node.

Here's an example of adding elements to the linked list:

TEXT/X-JAVA
1ll.add(10);
2ll.add(20);
3ll.add(30);

To display the elements of the linked list, we start at the head and traverse the list, printing the value of each node.

TEXT/X-JAVA
1ll.display();

The output of the above code would be:

SNIPPET
110
220
330
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment