07 - 09/15/10 19:00:58 CS 61B: Lecture 7 Monday, September...

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

View Full Document Right Arrow Icon
09/15/10 19:00:58 1 07 CS 61B: Lecture 7 Monday, September 13, 2010 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.
Background image of page 1

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

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/10/2012 for the course CS 61B taught by Professor Canny during the Fall '01 term at Berkeley.

Page1 / 2

07 - 09/15/10 19:00:58 CS 61B: Lecture 7 Monday, September...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online