
Concept explainers
Using Java, modify the doubly linked list class presented below so it works with generic types. Add the following methods drawn from the java.util.List interface:
• void clear(): remove all elements from the list.
• E get(int index): return the element at position index in the list.
• E set(int index, E element): replace the element at the specified position with the specified element and return the previous element.
Test your generic linked list class by processing a list of numbers of type double.
====================================
/**
The DLinkedList class implements a doubly Linked list.
*/
class DLinkedList {
/**
The Node class stores a list element and a reference to the next node.
*/
private class Node
{
String value; // Value of a list element
Node next; // Next node in the list
Node prev; // Previous element in the list
/**
Constructor.
@param val The element to be stored in the node.
@param n The reference to the successor node.
@param p The reference to the predecessor node.
*/
Node(String val, Node n, Node p)
{
value = val;
next = n;
prev = p;
}
/**
Constructor.
@param val The element to be stored in the node.
*/
Node(String val)
{
// Just call the other (sister) constructor
this(val, null, null);
}
}
private Node first; // Head of the list
private Node last; // Last element on the list
/**
Constructor.
*/
public DLinkedList()
{
first = null;
last = null;
}
/**
The isEmpty method checks to see if the list is empty.
@return true if list is empty, false otherwise.
*/
public boolean isEmpty()
{
return first == null;
}
/**
The size method returns the length of the list.
@return The number of elements in the list.
*/
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count ++;
p = p.next;
}
return count;
}
/**
The add method adds to the end of the list.
@param e The value to add.
*/
public void add(String e)
{
if (isEmpty())
{
last = new Node(e);
first = last;
}
else
{
// Add to end of existing list
last.next = new Node(e, null, last);
last = last.next;
}
}
/**
This add method adds an element at an index.
@param e The element to add to the list.
@param index The index at which to add.
@exception IndexOutOfBoundsException When the index is out of bounds.
*/
public void add(int index, String e)
{
if (index < 0 || index > size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Index is at least 0
if (index == 0)
{
// New element goes at beginning
Node p = first; // Old first
first = new Node(e, p, null);
if (p != null)
p.prev = first;
if (last == null)
last = first;
return;
}
// pred will point to the predecessor
// of the new node.
Node pred = first;
for (int k = 1; k <= index - 1; k++)
{
pred = pred.next;
}
// Splice in a node with the new element
// We want to go from pred-- succ to
// pred--middle--succ
Node succ = pred.next;
Node middle = new Node(e, succ, pred);
pred.next = middle;
if (succ == null)
last = middle;
else
succ.prev = middle;
}
/**
The toString method computes the string representation of the list.
@return The string representation of the linked list.
*/
public String toString()
{
StringBuilder strBuilder = new StringBuilder();
// Use p to walk down the linked list
Node p = first;
while (p != null)
{
strBuilder.append(p.value + "\n");
p = p.next;
}
return strBuilder.toString();
}
/**
The remove method removes the element at a given position.
@param index The position of the element to remove.
@return The element removed.
@exception IndexOutOfBoundsException When index is out of bounds.
*/
public String remove(int index)
{
if (index < 0 || index >= size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Locate the node targeted for removal
Node target = first;
for (int k = 1; k <= index; k++)
target = target.next;
String element = target.value; // Element to return
Node pred = target.prev; // Node before the target
Node succ = target.next; // Node after the target
// Route forward and back pointers around
// the node to be removed
if (pred == null)
first = succ;
else
pred.next = succ;
if (succ == null)
last = pred;
else
succ.prev = pred;
return element;
}
/**
The remove method removes an element from the list.
@param element The element to remove.
@return true if the element was removed, false otherwise.
*/
public boolean remove(String element)
{
if (isEmpty())
return false;
// Locate the node targeted for removal
Node target = first;
while (target != null
&& !element.equals(target.value))
target = target.next;
if (target == null)
return false;
Node pred = target.prev; // Node before the target
Node succ = target.next; // Node after the target
// Route forward and back pointers around
// the node to be removed
if (pred == null)
first = succ;
else
pred.next = succ;
if (succ == null)
last = pred;
else
succ.prev = pred;
return true;
}
public static void main(String [] args)
{
DLinkedList ll = new DLinkedList();
ll.add("Amy");
ll.add("Bob");
ll.add(0, "Al");
ll.add(2, "Beth");
ll.add(4, "Carol");
System.out.println("The elements of the list are:");
System.out.println(ll);
}
}

Trending nowThis is a popular solution!
Step by stepSolved in 6 steps with 4 images

- In python. Write a LinkedList class that has recursive implementations of the add and remove methods. It should also have recursive implementations of the contains, insert, and reverse methods. The reverse method should not change the data value each node holds - it must rearrange the order of the nodes in the linked list (by changing the next value each node holds). It should have a recursive method named to_plain_list that takes no parameters (unless they have default arguments) and returns a regular Python list that has the same values (from the data attribute of the Node objects), in the same order, as the current state of the linked list. The head data member of the LinkedList class must be private and have a get method defined (named get_head). It should return the first Node in the list (not the value inside it). As in the iterative LinkedList in the exploration, the data members of the Node class don't have to be private. The reason for that is because Node is a trivial class…arrow_forwardImplement a simple linked list in Python (Write source code and show output) with basic linked list operations like: (a) create a sequence of nodes and construct a linear linked list. (b) insert a new node in the linked list. (b) delete a particular node in the linked list. (c) modify the linear linked list into a circular linked list. Use this template: class Node:def __init__(self, val=None):self.val = valself.next = Noneclass LinkedList:"""TODO: Remove the "pass" statements and implement each methodAdd any methods if necessaryDON'T use a builtin list to keep all your nodes."""def __init__(self):self.head = None # The head of your list, don't change its name. It shouldbe "None" when the list is empty.def append(self, num): # append num to the tail of the listpassdef insert(self, index, num): # insert num into the given indexpassdef delete(self, index): # remove the node at the given index and return the deleted value as an integerpassdef circularize(self): # Make your list circular.…arrow_forwardJAVA please Given main() in the ShoppingList class, define an insertAtEnd() method in the ItemNode class that adds an element to the end of a linked list. DO NOT print the dummy head node. Ex. if the input is: 4 Kale Lettuce Carrots Peanuts where 4 is the number of items to be inserted; Kale, Lettuce, Carrots, Peanuts are the names of the items to be added at the end of the list. The output is: Kale Lettuce Carrots Peanuts Code provided in the assignment ItemNode.java:arrow_forward
- Given main.py and a PersonNode class, complete the PersonList class by writing find_first() and find_last() methods at the end of the PersonList.py file. The find_first() method should find the first occurrence of an age value in the linked list and return the corresponding node. Similarly, the find_last() method should find the last occurrence of the age value in the linked list and return the corresponding node. For both methods, if the age value is not found, None should be returned. The program will replace the name value of each found node with a new name. Ex. If the input is: Alex 23 Tom 41 Michelle 34 Vicky 23 -1 23 Connor 34 Michela main.py(can not edit) from PersonNode import PersonNodefrom PersonList import PersonList if __name__ == "__main__": person_list = PersonList() # Read input lines until encountering '-1' input_line = input() while input_line != '-1': split_input = input_line.split(' ') name = split_input[0] age =…arrow_forwardImplement a Single linked list to store a set of Integer numbers (no duplicate) • Instance variable• Constructor• Accessor and Update methods 3. Define TestSLinkedList Classa. Declare an instance of the Single List class.b. Test all the methods of the Single List class.arrow_forwardGiven the source code of linked List, answer the below questions(image): A. Fill out the method printList that print all the values of the linkedList: Draw the linked list. public void printList() { } // End of print method B. Write the lines to insert 10 at the end of the linked list. You must draw the final linked List. Notice that you can’t use second or third nodes. Feel free to define a new node. Assume you have only a head node C. Write the lines to delete node 2. You must draw the final linked list. Notice that you can’t use second or third node. Feel free to define a new node. Assume you have only a head nodearrow_forward
- Java Solution with explanation in detailed please!arrow_forwardJava's LinkedList provides a method listlterator(int index) returning a Listlterator for a list. Declare a variable of LinkedList of integer numbers and write a fragment of Java code to compute and print the sum of the numbers on the list. Do not write code to insert elements to the list and assume that the list already has elements on it. You must only use an iterator obtained from the list (you can not use the get(int index) method) .arrow_forwardSuppose you have created a new class: SortedLinkedList. This class is derived from LinkedList (single links). You are asked to overload the method Insert. The method Insert will no longer take in a parameter position, this is because now Insert will place the element in the correct position such that the list is always sorted. Write the C++ code for the implementation of that Insert method.arrow_forward
- Java Design and draw a method called check() to check if characters in a linked list is a palindrome or not e.g "mom" or "radar" or "racecar. spaces are ignored, we can call the spaces the “separator”. The method should receive the separator as a variable which should be equal to “null” when no separator is used.arrow_forwardPlease fill in all the code gaps if possible: (java) public class LinkedList { privateLinkedListNode head; **Creates a new instance of LinkedList** public LinkedList () { } public LinkedListNode getHead() public void setHead (LinkedListNode head) **Add item at the front of the linked list** public void insertFront (Object item) **Remove item at the front of linked list and return the object variable** public Object removeFront() }arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education





