{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# 07 - 02:38:20 CS 61B Lecture 7 Wednesday February 4 2009...

This preview shows pages 1–2. Sign up to view the full content.

02/05/09 02:38:20 1 07 CS 61B: Lecture 7 Wednesday, February 4, 2009 Today’s reading: LISTS ===== We can store a list of ints as an array, but there are disadvantages to this representation. First, arrays have a fixed length that can’t be changed. If we want to add items to a list, but the array is full, we have to allocate a whole new array, and move all the ints from the old array to the new one. Second, if we want to insert an item at the beginning or middle of an array, we have to slide a lot of items over one place to make room. This takes time proportional to the length of the array. public class List { int a[]; int lastItem; public List() { a = new int[10]; // The number "10" is arbitrary. lastItem = -1; } public void insertItem(int newItem, int location) { int i; if (lastItem + 1 == a.length) { int b[] = new int[2 * a.length]; // Allocate a new array, twice as long. for (i = 0; i <= lastItem; i++) { // Copy items to the bigger array. b[i] = a[i]; } a = b; // Replace the too-small array with the new one. } for (i = lastItem; i >= location; i--) { // Shift items to the right. a[i + 1] = a[i]; } a[location] = newItem; lastItem++; } } LINKED LISTS (a recursive data type) ============ We can avoid these problems by choosing a Scheme-like representation of lists. A linked list is made up of "nodes". Each node has two components: an item, and a reference to the next node in the list. These components are analogous to "car" and "cdr". However, our node is an explicitly defined object. public class ListNode { // ListNode is a recursive type public int item; public ListNode next; // Here we’re using ListNode before } // we’ve finished declaring it. Let’s make some ListNodes.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 2

07 - 02:38:20 CS 61B Lecture 7 Wednesday February 4 2009...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online