CS 46B - Lecture 18

Cover page image

Pre-class reading

Object Diagrams

Object Diagrams

.jpg

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)

Clicker Question

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

Implementing Stacks and Queues

Stacks as Linked Lists

Clicker Question

Where should the nodes be added/removed for maximum efficiency?

  1. push adds before first, pop removes last
  2. push adds before first, pop removes first
  3. push adds after last, pop removes last
  4. push adds after last, pop removes first

Stacks as Array Lists

Clicker Question

Where should the elements be added/removed for maximum efficiency?

  1. push adds before first, pop removes last
  2. push adds before first, pop removes first
  3. push adds after last, pop removes last
  4. push adds after last, pop removes first

Queues as Linked Lists

Clicker Question

Where should the nodes be added/removed for maximum efficiency?

  1. add adds before first, remove removes last
  2. add adds before first, remove removes first
  3. add adds after last, remove removes last
  4. add adds after last, remove removes first

Queues as Circular Arrays

Clicker Question

Assume the buffer has size 10. What is its contents after these operations?

for (i = 1; i <= 8; i++) q.add(i);
for (i = 1; i <= 4; i++) q.remove();
for (i = 1; i <= 8; i++) q.add(i);
for (i = 1; i <= 4; i++) q.remove();
  1. 1 2 3 4 5 6 7 8
  2. 3 4 5 6 7 8 7 8 1 2
  3. 3 4 5 6 7 8 0 0 1 2
  4. Something else