Question

The add(index, e) method inserts an element into the list at the specified index. It can...

The add(index, e) method inserts an element into the list at the specified index. It can be implemented as follows:

public void add(int index, E e) {

     if (index == 0) addFirst(e); // Insert first

     else if (index >= size) addLast(e);// Insert last

     else { // Insert in the middle

     Node<E> current = head;

         

     for (int i = 1; i < index; i++)

          current = current.next;

     Node<E> temp = current.next;

     current.next = new Node<E>(e);

     (current.next).next = temp;

     size++;

     }

}

Using the above code snippet, your author states that “There are three cases when inserting an element into the list”.

Describe the three cases when inserting an element into the list (Need more than one sentence to describe each case)

  1. ________________
  1. ________________
  1. ________________
0 0
Add a comment Improve this question Transcribed image text
Answer #1

ANSWER

While inserting a node to a list, there are 3 possible scenarios:

  • Insert at the beginning
  • Insert at the end
  • Insert at middle (Specified position)

SCENARIO – 1: Insert at the beginning:

  • If the index passed to the function is 0, then that means, the passed element is to be inserted at the beginning of the list. This can be done by,
    • Create a temp node using the element passed
      • Node <E> temp = new Node<E>(e)
    • Point the next of temp node to head
      • temp.next = head
    • make the temp node as the new head
      • temp = head
    • Increment the size of list
    • Now, the passed node is inserted at the beginning

SCENARIO – 2: Insert at the end:

  • If the passed index is greater than or equal to the size of the list (Probably equal to the size of the list), the passed element should be inserted at the end
    • Create a temp node using the element passed
      • Node <E> temp = new Node<E>(e)
    • Create a current element and make it point to head
      • Node <E> current = head
    • Iterate the current element “SIZE OF THE LIST TIMES” by doing,
      • current = current.next
    • After iterating the list, size times, point the next of current to temp node
      • current.next = temp
    • Increment the size of list
    • Now, the element passed is inserted at the end of the list

SCENARIO – 3: Insert at the middle (Specified index):

  • If the passed index is not 0, not equal to size of list, then the element has to be inserted somewhere in the middle of the list. To do this,
    • Create a current node and point it to head of the list
      • Node <E> current = head
    • Iterate the list “index” times starting from head
      • Current = current.next;
    • Once desired position is reached, create a temp node to hold the rest of the elements of the list from current.next ‘s position
      • Node <E> temp = current.next
    • Now point the current.next to the new node
      • current.next = new Node<E>(e)
    • Now that new element is added at current.next, add the rest of the list fter new added node by pointing current.next.next to temp (which temporarily holds the rest of elements)
      • (current.next).next = temp
    • Increment the size of list
    • Now the element passed is added to the desired position
Add a comment
Know the answer?
Add Answer to:
The add(index, e) method inserts an element into the list at the specified index. It can...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Add a method to the DoubleLinkedList class built in class to reverse every set of values...

    Add a method to the DoubleLinkedList class built in class to reverse every set of values For example: 1, 2, 3, 4, 5, 6 Reverse 3: 3,2,1,6,5,4 Reverse 2: 2,1,4,3,6,5 Reverse 6: 6,5,4,3,2,1 Method header: public void reverseSegments(int setSize) outcome should be like this: Input:​​​​​​​​​​​​​​ 3 1 2 3 4 5 6 output: 3 2 1 6 5 4 Input:​​​​​​​​​​​​​​​​​​​​​ 2 ​​​​​​​1 2 3 4 5 6 output: 2 1 6 5 4 3 ============================================code====================================================================== public class MyDoubleLinkedList<E> { private...

  • PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None   

    PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None        self.__size = 0    # Return the head element in the list    def getFirst(self):        if self.__size == 0:            return None        else:            return self.__head.element        # Return the last element in the list    def getLast(self):        if self.__size == 0:            return None        else:            return self.__tail.element    # Add an element to the beginning of the list    def addFirst(self, e):        newNode = Node(e) # Create a new node        newNode.next = self.__head # link...

  • JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has...

    JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has you display a pessimistic poem from a list of phrases. Next, this program has you reverse the phrases to find another more optimistic poem. Use the following algorithm. 1.   You are given a list of phrases each ending with a pound sign: ‘#’. 2.   Create a single String object from this list. 3.   Then, split the String of phrases into an array of phrases...

  • Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)...

    Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)    {        this.size = size;    }    /** Reference to list head. */    private Node<E> head = null;    /** The number of items in the list */    private int size = 0;       /** Add an item to the front of the list.    @param item The item to be added    */    public void addFirst(E...

  • Java - I need help creating a method that removes a node at the specific index...

    Java - I need help creating a method that removes a node at the specific index position. The * first node is index 0. public boolean delAt(int index) { src code 2 different classes ******************************************** public class Node { private String data; private Node next; public Node(String data, Node next) { this.data = data; this.next = next; } public Node() { } public String getData() { return data; } public void setData(String data) { this.data = data; } public void...

  • Hi! Can someone can convert this java code to c++. ASAP thanks I will thumbs up Here's the code: ...

    Hi! Can someone can convert this java code to c++. ASAP thanks I will thumbs up Here's the code: package lists; import bookdata.*; public class DoublyLinkedList { int size; //Variable que define el tamano de la lista. Node head, tail; //Nodos que definen el Head y Tail en la lista. //Constructor public DoublyLinkedList(){ this.head = null; this.tail = null; this.size = 0; } //Insert a new book in alphabetic order. public void insert(Book nb){ //Creamos uno nuevo nodo con el...

  • Doubly Linked List Java Help Details: First, read the DoublyLinkedList.java code and try to under...

    Doubly Linked List Java Help Details: First, read the DoublyLinkedList.java code and try to understand what each field stores and what each method is doing. Modify and complete the class as described below •The field size was defined in the class but was never maintained. Set the current default value and modify it whenever it is needed in the existing methods and other methods you implement as it is needed. It should always include the number of Nodes inside the...

  • Consider java for fixing this code please: what i need is to insert method to be...

    Consider java for fixing this code please: what i need is to insert method to be added ( please don't change the test class and any giving value in the first class ) here is the correct out put: ------------------testAddLast()---- {A} {A->B} {A->B->null} {A->B->null->C} ----------------------------- --------testSubListOfSmallerValues()---------- {} {B->B->B->A} {F->B->B->B->A->D} {F->B->B->G->B->A->M->D} ----------------------------- ------------Test lastIndexOf()----- -1 3 -1 -1 0 5 2 ----------------------------- ---------testRetainAll()--------- {} {6:Tony->6:Tony} {null->bad->null} ----------------------------- ---------------Test removeStartingAtBack--- false true {apple->null->bad->null} true {apple->null->bad} {2:Morning->3:Abby->4:Tim->5:Tom->6:Tony} ----------------------------- ---------test insertionSort()--------- {} {D} {D->E->E->F->G}...

  • Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements...

    Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...

  • Improve the speed of public T get(int i) by having it work backward from the end...

    Improve the speed of public T get(int i) by having it work backward from the end of the array if you attempt to get a member which is closer to the end than the start. This improvement will be tested through timing tests on large lists. The method should still return null if i is not a valid index. Code import java.util.Iterator; public class DLList<T> implements Iterable<T> {    private static class Node<T> {        public Node<T> prev, next;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT