Tasmin Tasmin - 3 months ago 8
Java Question

Adding data last in linkedlist

I am trying to add data in the last a link list. Here is my code.
This is my Linked list class:

public class LinkedList {
Node head;

private static class Node {
int data;
Node pointer;

public Node(int data) {
this.data=data;
pointer=null;
}
}


this method is for appending data in last.

public void append(int new_data){
Node new_node=new Node (new_data);

if (head==null){
head=new Node(new_data);

}
Node last_node=head;
new_node.pointer=null;
while (last_node.pointer !=null){
last_node=last_node.pointer;
last_node.pointer=new_node;

}
}


this method is to print the data.

public void printData(){
Node print_Node;
print_Node=head;
while (print_Node !=null){
System.out.print(print_Node.data+" ");
print_Node=print_Node.pointer;
}

}

public static void main(String[] args) {
LinkedList obj=new LinkedList();

obj.append(10);
obj.append(100);
obj.printData();

}
}


Where is the problem in my code? It only prints 10.

Answer

TRY THIS OUT

public class linked_list {

Node head;

private static class Node

{
    int data;
    Node pointer;

    public Node(int data)
    {
        this.data = data;
        pointer = null;
    }
}

    public void append(int new_data)
    {
        Node new_node = new Node(new_data);
        //new_node.pointer = null;  No need to set pointer to null as it is already null in your constructor.

        if (head == null)
        {
            head = new Node(new_data);
        }

        Node last_node = head; // Its okay To not change head , good practise.
        while (last_node.pointer != null)
        {
            last_node = last_node.pointer;
        }
        // I think here was the error, your the linked list was not adding only one element , Because while loop
       // got terminated just it reaches null i.e not executing the below line.
        // So put it after while loop, wen you have reached the NULL.
        last_node.pointer = new_node; // line ERROR

    }
    public void printData(){
        Node print_Node;
        print_Node=head;
        while (print_Node !=null){
            System.out.print(print_Node.data+" ");
            print_Node = print_Node.pointer;
        }

    }
    public static void main(String[] args)
    {
        linked_list obj=new linked_list();

        obj.append(10);
        obj.append(100);
        obj.append(898);
        obj.append(8334);
        obj.append(118334);
        obj.append(833400);
        obj.append(83340043);

        obj.printData();

    }

}