Question: public class DoublyLinkedList { private static class Node { /** The element stored at this node */ private E element; // reference to the element
public class DoublyLinkedList
private static class Node
/** The element stored at this node */ private E element; // reference to the element stored at this node
/** A reference to the preceding node in the list */ private Node
/** A reference to the subsequent node in the list */ private Node
public Node(E e, Node
public E getElement() { return element; }
public Node
public Node
public void setPrev(Node
public void setNext(Node
// instance variables of the DoublyLinkedList /** Sentinel node at the beginning of the list */ private Node
/** Sentinel node at the end of the list */ private Node
/** Number of elements in the list (not including sentinels) */ private int size = 0; // number of elements in the list
/** Constructs a new empty list. */ public DoublyLinkedList() { header = new Node<>(null, null, null); // create header trailer = new Node<>(null, header, null); // trailer is preceded by header header.setNext(trailer); // header is followed by trailer }
public int size() { return size; }
public boolean isEmpty() { return size == 0; }
public E first() { if (isEmpty()) return null; return header.getNext().getElement(); // first element is beyond header }
public E last() { if (isEmpty()) return null; return trailer.getPrev().getElement(); // last element is before trailer }
public void addFirst(E e) { addBetween(e, header, header.getNext()); // place just after the header }
public void addLast(E e) { addBetween(e, trailer.getPrev(), trailer); // place just before the trailer }
public E removeFirst() { if (isEmpty()) return null; // nothing to remove return remove(header.getNext()); // first element is beyond header } public E removeLast() { if (isEmpty()) return null; // nothing to remove return remove(trailer.getPrev()); // last element is before trailer }
private void addBetween(E e, Node
private E remove(Node
public String toString() { StringBuilder sb = new StringBuilder("("); Node
In this exercise, you will use the DoublyLinkedList implementation of above example. Write a method for concatenating two doubly linked lists , with header and trailer sentinel nodes, into a single list L. Write a main method to test the new method. Hint: Connect the end of L into the beginning of M.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
