MyDLL - Node<E> nextItem = head; for...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
class Node<E> { E data; Node<E> next = null; Node<E> prev = null; public Node(E dataItem) { data = dataItem; } } } public class MyDLL<E> { private Node<E> head = null; private Node<E> tail = null; private int size = 0; public int size() { return size; } public E get(int index) { if (index < 0 || index >= size) throw new IndexOutOfBoundsException("Invalid index " + index); Node<E> item = head; for (int i = 0; i < index; i++) item = item.next; return item.data; } public void add(int index, E obj) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Invalid index " + index); Node<E> newNode = new Node < E > (obj); if (head == null) { // Add to an empty list. head = newNode; tail = head; } else if (index == 0) { // Insert at head. newNode.next = head; //Step 1 head.prev = newNode; // Step 2 head = newNode; // Step 3 } else if (index == size) { // Insert at tail. tail.next = newNode; // Step 1 newNode.prev = tail; // Step 2 tail = newNode; // Step 3 } else { // Insert into the middle.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Node&lt;E&gt; nextItem = head; for (int i = 0; i &lt; index; i++) nextItem = nextItem.next; newNode.prev = nextItem.prev; // Step 1 nextItem.prev.next = newNode; // Step 2 newNode.next = nextItem; // Step 3 nextItem.prev = newNode; // Step 4 } size++; } public E remove(int index) { if (index &lt; 0 || index &gt;= size) throw new IndexOutOfBoundsException(&quot;Invalid index &quot; + index); E retval = null; if(index == 0) { retval = head.data; head = head.next; head.prev = null; size--; return retval; } if(index == size - 1) { retval = tail.data; tail = tail.prev; tail.next = null; size--; return retval; } Node &lt;E&gt; item = head; for (int i = 0; i &lt; index; i++) item = item.next; item.prev.next = item.next; item.next.prev = item.prev; size--; return item.data; } public void addFirst(E item) { add(0, item); } public void addLast(E item) { add(size, item); } public E removeFirst() { return remove(0); } public E removeLast() { return remove(size - 1); } }...
View Full Document

This note was uploaded on 03/25/2010 for the course CIS CIS3023 taught by Professor Seema during the Spring '10 term at Florida College.

Page1 / 2

MyDLL - Node&amp;amp;lt;E&amp;amp;gt; nextItem = head; for...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online