90 likes | 225 Views
CSC 205 Programming II. Lecture 13 Linked List – The Concept. Recap: Array List. ArrayList list = new ArrayList();. add. size. remove. get. items. numItems. …. pde1. pde2. pde3. pde4. pde5. pde6. 6. pde1:PhoneDirectoryEntry. name = “John, Bill” number = “3469127856”. ….
E N D
CSC 205 Programming II Lecture 13 Linked List – The Concept
Recap: Array List ArrayList list = new ArrayList(); add size remove get items numItems … pde1 pde2 pde3 pde4 pde5 pde6 6 pde1:PhoneDirectoryEntry name = “John, Bill” number = “3469127856” … …
Array List: tradeoffs • Advantages • An order is imposed on elements due to the physical sequence in the underlying array • Elements can be randomly accessed • Disadvantages • Efforts needed to shift the rear portion of the array when an non-tail item is added/deleted • Efforts needed to expand the array when it becomes full
Resizeable Arrays add size remove get capacity capacityIncrement items 50 0 numItems … pde1 pde2 pde3 pde4 pde5 pde6 pde7 pde8 pdex pdey capacity if (capacityIncrement == 0) capacity *= 2; else capacity += capacityIncrement ; See: WM p158 King p207
ArrayList: Size Expanded add size remove get capacity capacityIncrement items 100 0 numItems … pde1 pde2 pde3 pde4 pde5 pde6 pde7 pde8 pdex pdey capacity/2 … newArray = new Object[capacity]; newArray = System.arraycopy(items,0, newArray,0,capacity); items = newArray;
Linked List • An order is imposed due to an item’s reference to its successor • An item is stored in a node, which consists • The item, and • A reference to its successor add size remove get numItems head x node … pde1 pde2 pde3 pdex
Linked List – insertion and deletion • Insertion into or deletion from the middle of a linked list is easy: reset the reference • Break the old link • Set up a new link … pde1 pde2 pde3 pdex insertion pde2 inserted item deletion … pde1 pde2 pde3 pdex deleted item
Implementation - Reference-Based • A LinkedList class should • Use a Node class – to hold the items • Implement an appropriate list interface – to comply to the contracts as specified ListInterface LinkedList Node
The Node Class • Instance variables • The item: item • to be generic, the type Object is used • The reference: next • Q: What type should it be in? • A: Node itself! • Constructors • Instance methods Node -item:Object -next:Node +Node(item) +Node(item,next) +getItem():Object +setItem(item) +getNext():Node +setNext(next)