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
  • Python Program Only: Write the function definition only of the "get(self, index)" function. Plug your method...

    Python Program Only: Write the function definition only of the "get(self, index)" function. Plug your method in the code file shared with you and test it in the main to get the element at index 3 of mylist2 . class Node: def __init__(self, e): self.element = e self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None self.size = 0 def addFirst(self, e): newNode = Node(e) newNode.next = self.head self.head = newNode self.size = self.size + 1...

  • 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...

  • 1. Create a node class and linked list class. 2. Add the following function from lecture...

    1. Create a node class and linked list class. 2. Add the following function from lecture to your linked list class addFirst(e) addLast (e) add(index, e) removeFirst removeLast remove(index) 3. Add the following methods to the linked list class. a. # Return the size of the list def getSize(self): b. # Clear the list */ def clear(self): c. # Return the element from this list at the specified index def get(self, index):

  • 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}...

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