X420: Insert In Middle

Consider the following class definitions:

public class LinkedChain<T> {
    private Node<T> firstNode;
    private int numberOfEntries;

    public LinkedChain() {
        firstNode = null;
        numberOfEntries = 0;
    }// end default constructor


    public Node<T> getfirstNode() {
        return firstNode;
    }


    public int getNumberOfEntries() {
        return numberOfEntries;
    }



    public void push(T newEntry) {
        // TODO Auto-generated method stub
        firstNode = new Node<T>(newEntry, firstNode);
        numberOfEntries++;
    }
}

Where Node is defined as:

public class Node<T> {
     private T data; // Entry in bag
     private Node<T> next; // Link to next node

     public Node(T dataPortion) {
         this(dataPortion, null);
     } // end constructor


     public Node(T dataPortion, Node<T> nextNode) {
         data = dataPortion;
         next = nextNode;
     } // end constructor


     public T getData() {
         if (data != null) {
             return data;
         }
         return null;
     }


     public Node getNext() {
         return next;
     }


     public void setNext(Node<T> newNext) {
         next = newNext;
     }
}

Below, write a Linked Chain method. This method will take in a node that is the start of a different linked chain. You will need to write the code to insert the second chain in the middle of the original chain.

Example 1: Even length case

For example, if the linked chain looked like this:

A --> B --> C --> D

And there was another linked chain object that looked like this:

X --> Y --> Z

the parameter list2Head for this method might be a reference to the node containing X.

this method would change the chain to:

A --> B --> X --> Y --> Z --> C --> D

Example 2: Odd length case

For example, if the linked chain looked like this:

A --> B --> C --> D --> E

And there was another linked chain object that looked like this:

X --> Y --> Z

the parameter list2Head for this method might be a reference to the node containing X.

this method would change the chain to:

A --> B --> C --> X --> Y --> Z --> D --> E

If the node referenced is null the code should not alter the linked chain. Remember to update the numberOfEntries variable!

Hint: You've already done a linked chain exercise about finding the middle of a linked chain. It may be helpful to review that!

Your Answer:

Reset
Visualize

Practice a different Java exercise

Feedback

Your feedback will appear here when you check your answer.