Linked List: Print the linked list

Question: Write a function print() function to print the entire linked list. Throw an exception if the linked list of empty

package additional_problems.linkedList;

/**
 * Created by aarushi on 24/6/21.
 */
public class LinkedList {
    //data fields
    //head node
    ListNode head;

    //constructor to initialize head node
    public LinkedList(){
        head=null;
    }

    //function to add node to the end of the linked list
    public void add(ListNode node){
        //if list is empty then set head equal to the node
        if(head==null){
            head = node;
            node.setNext(null);
        } else {
            //create a pointer- temp
            ListNode temp= head;
            //iterate to the last element
            while(temp.getNext()!=null){
              temp=temp.getNext();
            }
            //insert the node at the end of the list
            temp.setNext(node);
            node.setNext(null);
        }
    }


	//Method to print the linked list
    public void print() throws Exception{
        //if the list is empty, throw an exception
        if(head==null){
            throw new Exception("List is Empty");
        } else {
            ListNode temp=head; //create a pointer- temp that will traverse through the linked list
            while(temp!=null){ //traverse to the last element of the linked list
                System.out.print(temp.getData()+" "); //print the data of every node
                temp=temp.getNext();  //set pointer to the next node
            }
            System.out.println();
        }
    }
}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: