Implement a method to add(int data) to add a node to end of a linked list.
Assumptions
-
There is a class Node with two elements:
-
int data
-
Node next
-
-
There is a class LinkedList with a property head pointing to the first element of the linked list. Head may have null if the linked list has no elements. You need to add your new method to this class. You can assume it has all other required methods and works as expected.
-
There is a display method that may look like below:
-
Node current = head;
-
while(current!=null){
-
System.out.println(current.data);
-
current=current.next;
-
}
-
-
- Getters and setters need not be used for data and next for simplicity
-
All these classes are treated to be in a single package for simplicity
Testing
-
From a test class MyLinkedListTest you may invoke add method as:
-
MyLinkedListTest list = MyLinkedListTest();
-
list.add(1);
-
list.add(2);
-
list.add(3);
-
list.display();
-
public void add(int data){
Node end = new Node(data); //creating a new node
Node n = this; //providing the current object reference
while (n.next != null) {//checking till not null
n = n.next; //incrementing with the next node
}
n.next = end;//adding it at the end
}
Good attempt. But there needs to be some modifications: