[Updated] Goldman Sachs Aptitude Test Questions and Answers
Practice List of TCS Digital Coding Questions !!!
Take 50+ FREE!! Online Data Interpretation Mock test to crack any Exams.
Interview Questions and Answers :: Cisco

5. Write program to merge two linked lists?

Answer:

public class InsertNodeInLinkedList {

    static class Node{

        int data;

        Node next;

        Node(int d){

            data = d;

            next = null;

        }

    }

    

    

    static Node head;

    

    public static int length(Node head){

        if(head == null)

            return 0;

        //create count to hold the length

        int count = 0;

        Node curr = head;

        while(curr != null){

            count ;

            curr = curr.next;

        }

        return count;

    }

    

    public static Node insertNodeAtPosition(Node head, int data, int position){

        //boundary condition

        int size = length(head);

        if(position < 1 || position > size 1){

            System.out.println("Invalid position ...");

            return head;

        }

        

        Node newNode = new Node(data);

        //insert in 1st position

        if(position == 1){

            newNode.next = head;

            return newNode;

        }else{

            Node prevNode = head;

            int count = 1;

            while(count < position-1){

                prevNode = prevNode.next;

                count ;

            }

            

            Node currNode = prevNode.next;

            newNode.next = currNode;

            prevNode.next = newNode;

            return head;

        }

    }

    

    

    public static void main(String[] args) {

        InsertNodeInLinkedList list = new InsertNodeInLinkedList();

        list.head = new Node(85);

        list.head.next = new Node(15);

        list.head.next.next = new Node(5);

        list.head.next.next.next = new Node(10);

        System.out.println("Print the list");

        printList(head);

        System.out.println();

        head = insertNodeAtPosition(head, 20, 1);

        System.out.println("Insert 20 at position 1");

        printList(head);

        System.out.println();

        System.out.println();

        head = insertNodeAtPosition(head, 25, 4);

        System.out.println("Insert 25 at position 4");

        printList(head);

    }



    private static void printList(Node n) {

        while(n != null){

            System.out.print(n.data " ");

            n = n.next;

        }

    }

}

Post Your Answer Here:      Public      Private

Rate This: +0 -0
Report     

Post Your Reply Here:     

Report Error

Report Error

Please Login First Click Here