CS 46B - Lecture 18

Cover page image

Pre-class reading

Object Diagrams

Object Diagrams

Lecture 16 Paper Question 1

Look at my solution to Homework 10a.

Look at this test case.

Draw a diagram of what goes on in the call to names.reverseFirstN(2);.

Write your name and student ID on your sheet. When prompted, hand it to the front.

ArrayList Implementation

Get/Set

Removing

Lecture 18 Clicker Question 1

Consider the removeLast operation of an ArrayList, implemented as

public Object removeLast() { return remove(size() - 1); }

Which of the following is true about this operaton?

  1. It's O(n) since it calls remove which is O(n)
  2. Its' O(1) since it does a constant amount of work, independent of the array size
  3. It's O(n2) since both remove and size are O(n)
  4. It's O(log n) because the size of the problem is cut in half in each step

Adding

Growing the Buffer

Cost of n Additions

Amortized Cost

Comparing Linked Lists and Array Lists

Array List Doubly Linked List Singly Linked List
Add at end O(1)+ O(1) O(1)
Remove at    end O(1)+ O(1) O(n)
Add at head O(n) O(1) O(1)
Remove at head O(n) O(1) O(1)
Add in middle* O(n) O(1) O(1)
Remove in middle* O(n) O(1) O(1)

*Provided you are already there (with an integer index or iterator)

Lecture 18 Clicker Question 2

You want to add a zero directly in the middle of a sequence of integers (or replace the middle element with a zero  if the sequence has odd length). For example,

1 2 3 4 5 6 → 1 2 3 0 4 5 6

1 2 3 4 5 6 7 →1 2 3 0 5 6 7

Which data structure should you use for maximum efficiency

  1. An array list
  2. A doubly linked list
  3. Either an array list or a linked list—it does not matter
  4. A set