Download presentation
Presentation is loading. Please wait.
Published byFrank Patterson Modified over 9 years ago
1
“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
2
New Class: IntegerList Same public methods as IntegerVector –Clients will see almost no difference Very different “internal” implementation
3
IntegerList first, numElements add, get, set, position, remove, length Class Diagram
4
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
5
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
6
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
7
A Linked List Made up of many ListNode objects “linked” together by the next fields ListNode data next -56193-2
8
Locating the First Element in the List We use the first member of the IntegerList class ListNode data next -56193-2 IntegerList first numElements 4
9
Implementation of the Class Constructor –Must create an “empty” list public IntegerList () // Constructor { first = null; numElements = 0; } // constructor IntegerList first numElements 0
10
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
11
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
12
More Flexibility: Adding Nodes at Any Position Need to work through the linked list to find the correct position
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.