SLIDE 1
Week 4 -Wednesday What did we talk about last time? Finished array - - PowerPoint PPT Presentation
Week 4 -Wednesday What did we talk about last time? Finished array - - PowerPoint PPT Presentation
Week 4 -Wednesday What did we talk about last time? Finished array implementation of queues Started linked lists I'm glad you asked They allow a collection to be used in a foreach loop So, what's a foreach loop? public
SLIDE 2
SLIDE 3
SLIDE 4
SLIDE 5
SLIDE 6
SLIDE 7
I'm glad you asked They allow a collection to be used in a foreach loop So, what's a foreach loop? It allows you to read (but not change) each value in a list public static int sum( int[] array ) { int total = 0; for( int value: array ) total += value; return total; }
SLIDE 8
Foreach loops work for any iterable list of any type
public static double weigh(LinkedList<Wombat> list) { double total = 0.0; for( Wombat wombat: list ) total += wombat.getWeight(); return total; } public static double weigh(ArrayList<Wombat> list) { double total = 0.0; for( Wombat wombat: list ) total += wombat.getWeight(); return total; } public static double weigh(Wombat[] list) { double total = 0.0; for( Wombat wombat: list ) total += wombat.getWeight(); return total; }
SLIDE 9
Node consists of data and a single next pointer Advantages: fast and easy to implement Disadvantages: forward movement only
X
head 23 47 58
SLIDE 10
Node consists of data, a next pointer, and a previous pointer Advantages: bi-directional movement Disadvantages: slower, 4 pointers must change for every
insert/delete
X
head 23 47 58
X
tail
SLIDE 11
You are given a singly linked list It may have a loop in it, that is, a node that points back to an
earlier node in the list
If you try to visit every node in the list, you’ll be in an infinite
loop
How can you see if there is a loop in a linked list?
SLIDE 12
Let’s try a simple definition for a singly linked list:
public class LinkedList { private static class Node { public int data; public Node next; } private Node head = null; public int size = 0; … }
SLIDE 13
SLIDE 14
SLIDE 15
SLIDE 16
SLIDE 17
Assuming that the list has been kept in order
SLIDE 18
SLIDE 19
SLIDE 20
Implementation of a linked list with an iterator Circular linked lists and skip lists Implementing a stack with a linked list Implementing a queue with a linked list Keep reading section 1.3
SLIDE 21
Keep reading section 1.3 Finish Assignment 2
- Due Friday by midnight
Keep working on Project 1
- Don't fall behind!