Mayur Tolani
Mayur Tolani

Reputation: 1487

how to insert element at last in linked list

I have to implement insertAtLast() in a linked list.

I am getting a Null Pointer Exception in the code that i have written for insertAtLast(). Its maybe because I am Accessing it wrong.

How can I access it correctly and make the insertion too?

class myLinkedList {
private static class Node 
{
    private int data; 
    private Node next;

    public Node(int data, Node next) 
    {
        this.data = data;
        this.next = next; 
    }
}

private Node head;

// Constructs an empty list
public myLinkedList() 
{
    head = null; 
}

// Returns true if the list is empty otherwise returns false
public boolean isEmpty() 
{
    return (head == null); 
}

// Inserts a new node at the beginning of this list.    
public void insertAtBeginning(int element) 
{
    head = new Node(element, head); 
}

// Returns the first element in the list.
public int getFirstElement() 
{
    if(head == null) 
    {
        System.out.println("Empty linked list"); 
        throw new IndexOutOfBoundsException();
    }
    return head.data; 
}

// Removes the first node in the list.
public int removeFirstNode() 
{ 
    int tmp = getFirstElement(); 
    head = head.next;
    return tmp;
}

// Empties linked list 
public void clear() 
{
    head = null; 
}

// Returns the length of the linked list
public static int LLlength(Node head)
{ 
    int length = 0;
    Node currentNode = head; 

    while(currentNode != null)
    {
        length++;
        currentNode = currentNode.next; 
    }
    return length; 
}

// Displays the linked list elements
public static void display(Node head)
{ 
    if(head == null) 
    {
        System.out.println("Empty linked list");
        throw new IndexOutOfBoundsException(); 
    }

    Node currentNode = head; 

    while(currentNode != null)
    {
        System.out.print(currentNode.data+" ");
        currentNode = currentNode.next; 
    }
    System.out.println();
}

// Displays the linked list elements in reverse order 
public static void displayReverse(Node head)
{
    if(head == null){} 
    else
    {
        Node currentNode = head; 
        displayReverse(currentNode.next); 
        System.out.print(currentNode.data+" ");
    } 
}
//Displays the linked list's last element
public static int getLastElement(Node head)
{
    Node currentNode = head; 

    while(currentNode.next != null)
    {
        currentNode = currentNode.next; 
    }
    return currentNode.data;
}
public static void insertAtLast(Node head,int element)
{
    Node newNode=null;
    newNode.data = element;
    newNode.next = null;
    while(head.next != null)
    {
        head = head.next; 
    }
    head = newNode;
    //return head;

}

//Tells if a sepeific element is in the Linked List or not
public static boolean searchFor(Node head, int element)
{
    Node currentNode = head; 
    boolean flag = false;
    while(currentNode != null)
    {
        if (currentNode.data == element)
        {
            flag = true;
            break;
        } 
        currentNode = currentNode.next;
    }
    return flag;
}

} 

Upvotes: 1

Views: 3749

Answers (3)

Amin J
Amin J

Reputation: 1209

First of all, why are a few of your methods static? They make sense to be a class method rather than static ones.

If you want to support adding to the end of a linked list, I would suggest you keep track of the tail of your list. Right now your insertAtLast is O(n) and you can easily change that to O(1) by storing a pointer to the end of your linked list.

It will add to the complexity of many other methods though. So you might have to update the other ones if you decide to go with a tail pointer. I'm not going to to the details of your other methods but only give you what your non-static insertAtLast would look like if you had a tail pointer.

public void insertAtLast(int element)
{
    Node newNode = new Node(element,null);

    if (head == null){ // you need to check for head, it may be null
       head = newNode;
    }

    if (tail == null){ // also, maybe there is no tail currently.
       tail = newNode;
       return;
    }

    //there is an existing tail, update it
    tail.next = newNode;
    tail = newNode;
}

Upvotes: 0

Chris Gong
Chris Gong

Reputation: 8229

Look at how your declaring the node object newNode. You're setting it equal to null instead of instantiating it to an actual object. Remember that null means an empty reference. Therefore, the next two lines of code will give you an error because you're trying to access member variables of "nothing". Since you have a Node class and constructor, use that instead of what you're doing now. Lastly, use a temp variable that points to head and use that temp pointer to traverse through the node. Because in what you had before, you would set the head to point to the new object in the linked list, which is the last element rather than the first,

public static void insertAtLast(Node head,int element)
{
    Node newNode= new Node(element,null);
    Node temp = head;
    while(temp.next != null)
    {
        temp = temp.next; 
    }
    temp.next = newNode;
    //return head;

}

Upvotes: 1

nail fei
nail fei

Reputation: 2319

there exists three troubles in your insertAtLast method.


  1. Node newNode=null; the newNode object is a null reference it don't reference a object of Node, you may change it into Node newNode = new Node(value,null)
  2. after your while loop the head will make a reference with the last Node object, your works will only make head make a reference with a new Node object, it make no effect to the list self, for this new object have nothing with list.
  3. after this method, the head will reference a new object of Node rather than the first of the List.

an alternative solution :

public static void insertAtLast(Node head,int element)
{
   Node newNode=new Node(0,null);
   newNode.data = element;
   newNode.next = null;
   Node temp = head;
   while(temp.next != null)
   {
       temp = temp.next; 
   }
   temp.next = newNode;
  //return head;
}

Upvotes: 1

Related Questions