Friday, March 9, 2007

Lecture 23

Linked Lists

  • alternative method for producing an array of arbitrary size
    • a collection of objects of the same type
    • contained in the wrapper object, which points (or contains a reference) to the next object in the list
  • declare public class myObject
public class ListNode
{
private myObject item;
private ListNode next;
public ListNode(){...}
public ListNode getNext() {return next}
public void setNext(ListNode next) {this.next = next}
}

  • initially the list is empty
    • ListNode head = null;
  • add elements to the end as required
    • first element:
      • head = new ListNode(); /*head points to head of chain*/
    • every subsequent slement
      • let ListNode tail be reference to the last element in the list
        • tail.setNext(new ListNode(...));
        • tail = tail.getNext(); // not mandatory to keep track of tail
  • if the list is empty then the head must be 'null'
  • next pointer in the last element must be null

Transversing the List

  • Items are arranged in order
    • the only way to get something from the list is to first access all previous elements

Example - retrieve the ith element
  • pass through i next pointers to find the one you want

ListNode = head;
int j;
for (j=0; (j

Example - find the last element

ListNode n = head;
if (n != null)
{
while (n.getNext() ! = null)
{n = n.getNext() }
}


1 comment:

Anonymous said...

Thank you