My ListT Double Linked List 6 G int
My. List<T> Double Linked List [6] G int size(); T get(int i); [1] B T set(int i, T item); int index. Of(T item); [0] A void add(T item); [5] F [3] D void add(int i, T item); C [2] [4] E T remove(int i); Object[] to. Array(); H [7] <K> K[] to. Array(K[] a); 10/24/2021 IT 179 1
tail head item 0 indices 0 10/24/2021 item 1 1 item 2 2 item 3 3 IT 179 item 4 4 item 5 5 item 6 6 2
Using an inner class for the internal nodes public class My. DLinked. List <T> implements My. List<T> { /***** This is an inner class for internal nodes ****/ private static class Node<E> { private E data; private Node<E> prey, next; private Node(E data, Node<E> prev, Node<E> next) { // Construct a node pointing to next this. data = data; this. prev = prev this. next = next; data } } /**** This is the end of the inner class Node<E> ******/ private Node<T> head, tail; private int size; public My. DLinked. List() { head = tail = null; size=0; } ………… 10/24/2021 IT 179 3
public void add(T item) { // append item to the tail if (size==0) { head = tail = new Node<T>(item, null); } else { tail = tail. next = new Node<T>(item, tail, null); } size++; } x head tail new node 10/24/2021 IT 179 4
/** * @see my. Util. My. List#add(int, java. lang. Object) */ public void add(int at, T item) { // insert item at at if (at < 0 || at > size) // no can do throw new Index. Out. Of. Bounds. Exception( "Index. Out. Of. Bounds. Exception: Can't add at "+at); if (at == size) { x add(item); } else { add. Before(get. Node(at), item); new. Node } } at node private void add. Before(Node<T> node, T item) { if (node == head) { xx head = head. prev = new Node<T>(item, null, head); } else { node. prev = node. prev. next = new Node<T>(item, node. prev, node); } size++; } 10/24/2021 IT 179 5
public T remove(int at) { if (head == null || at < 0 || at >= size) throw new Index. Out. Of. Bounds. Exception( "Inde. Out. Of. Bounds. Exception: Can't remove at "+at); Node<T> node = head; int count = 0; while (count != at) { x count++; node = node. next; } if (node == head) { at head = node. next; node if (head==null) tail=head; else head. prev = null; } else if (node == tail) { tail = tail. prev; tail. next = null; xx } else { node. prev. next = node. next; node. next. prev = node. prev; } size--; return node. data; } 10/24/2021 IT 179 6
/** This is the copy constructor */ public My. DLinked. List(My. DLinked. List<T> a) { if (a. head == null) { head = tail = null; size = 0; return; // nothing to copy } head = new Node<T>(a. head. data, null, a. head. next); size = a. size; Node<T> node = head; while (node. next != null) { node. next = new Node<T>(node. next. data, node. next); node = node. next; } tail = node; } head tail item 0 item 1 item 2 item 3 item 4 item 5 item 6 tail head 10/24/2021 IT 179 7
- Slides: 7