Basic Linked List operations in Java - Add node to end of a linked list

3 posts / 0 new
Last post
heartin
Basic Linked List operations in Java - Add node to end of a linked list

Implement a method to add(int data) to add a node to end of a linked list.

 

Assumptions

  1. There is a class Node with two elements:

    1. int data

    2. Node next

  2. 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.

    1. There is a display method that may look like below:

      1. Node current = head;

      2. while(current!=null){

      3. System.out.println(current.data);

      4. current=current.next;

      5. }

  3. Getters and setters need not be used for data and next for simplicity
  4. All these classes are treated to be in a single package for simplicity

 

Testing

  1. From a test class MyLinkedListTest you may invoke add method as:

    1. MyLinkedListTest list = MyLinkedListTest();

    2. list.add(1);

    3. list.add(2);

    4. list.add(3);

    5. list.display();

Was it useful?
infinitoz
public void add(int data){

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

}

Was it useful?
heartin
Good attempt. But there needs

Good attempt. But there needs to be some modifications:

  1. add method is part of class LinkedList with a variable head. So "this" pointer will denote LinkedList class and you cannot assign a LinkedList object to a Node object. It can be Node n = head; (See assumption 2 for more details)
  2. You will also need to handle the situation of whether the list is currently empty or not. Currently if the list is empty, n will be null and n.next will throw NullPointerException. You may use a short circuit operator or any other way to avoid this NullPointerException.
Was it useful?

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!