“When we quit thinking primarily about ourselves and our own self-preservation, we undergo a truly heroic transformation of consciousness.” – Joseph Campbell Thought for the Day
New Class: IntegerList Same public methods as IntegerVector –Clients will see almost no difference Very different “internal” implementation
IntegerList first, numElements add, get, set, position, remove, length Class Diagram
Internal Details public class IntegerList { private class ListNode { public int data; public ListNode next; } // class ListNode private ListNode first; // Pointer to the // first ListNode in an IntegerList private int numElements; // Number of // elements in an IntegerList... } // class IntegerList An Inner Class
The Inner Class ListNode ListNode is private, so can only be used inside IntegerList data and next are public, so can be accessed outside ListNode public class IntegerList { private class ListNode { public int data; public ListNode next; } // class ListNode... } // class IntegerList
Structure of a ListNode Object We can picture a single ListNode object as follows: ListNode data next -56 private class ListNode { public int data; public ListNode next; } // class ListNode
A Linked List Made up of many ListNode objects “linked” together by the next fields ListNode data next
Locating the First Element in the List We use the first member of the IntegerList class ListNode data next IntegerList first numElements 4
Implementation of the Class Constructor –Must create an “empty” list public IntegerList () // Constructor { first = null; numElements = 0; } // constructor IntegerList first numElements 0
Adding a New Element Simple Case: add as first element Need to –Create a new list node –Link it into the list public void add (int item) // Place the new item into a list { ListNode node = new ListNode(); node.data = item; node.next = first; first = node; numElements++; } // add
public void add (int item) { ListNode node = new ListNode(); node.data = item; node.next = first; first = node; numElements++; } // add ListNode data next 3-8 IntegerList first numElements 2 Adding 17 0 node 17 3
More Flexibility: Adding Nodes at Any Position Need to work through the linked list to find the correct position