Write an insert-by-position method in a linked list class. The list contains Str
ID: 3585921 • Letter: W
Question
Write an insert-by-position method in a linked list class. The list contains Strings, is doubly-linked and non-circular; it does not have a tail reference. Position is an incoming parameter, along with the String to be inserted. Assume a one-based position, meaning the first node in the list is number one, the second is two, and so forth. Insert in position three will make the new node third in the list. Insert in position one will make it the new head of the list.
Remember to handle the special case of an empty list. You may assume that the position number passed in is valid, meaning it will not be out of range for the list (if the list is size 5, the new position will be in the range 1 to 6, where 6 would be a new last node).
Match this sample call from outside the LinkedList class:
myList.insertByPosition(4, “cat”); // inserts a Node with “cat” in the fourth position
The head variable in the LinkedList class is named head. Here is Node class information (the same as we have been using, a private class inside the LinkedList class):
private class Node {
private String info;
private Node next, previous;
}
Explanation / Answer
private class Node {
private String info;
private Node next, previous;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.