CSC151, Class 29: Designing a List Type Overview: * What is a list? * Building the list data type in C. * Implementing key operations. * List cursors Notes: * Read chapter 9 of Gries for tomorrow. (A nice long chapter.) * How did Friday's class go? * Are there remaining questions on the code? I see that plans has a dialog on the readCity problem. * What causes segmentation faults? * Questions on exam 1? Seg Faults: "You idiot, you're using an invalid memory address". Why? (1) Accessing part of an array that's not there. (2) Uninitialized pointer. (3) Pointing explicitly to invalid locations (usually due to a type error). int *ip = (int *) 5; int i; scanf("%d", i); (4) Dereferencing null. Questions on exam 1 Exponentiation discussion Can we do it in better than O(log_2(n)) time? Idea: Change the base of the numbers? Suppose x is represented in base 2 (pretty easy assumption) What are some rules related to exponentiation? x^a * x^b = x^(a+b) Division algorithm Let n/2 be q remainder r x^n = x^q * x^r n/2 is a right shift x^r is either x or 1 (x^n)^m = x^(n*m) x^a / x^b = x^(a-b) x^2k = (x^2)^k What can we do with x? Can we express x in another way? x = e^ln(x) x^n = (e^ln(x))^n x^n = e^(n*ln(x)) If e^v is constant time and ln(w) is constant time, then this strategy is constant time. ---------------------------------------- What is a list? * Scheme + Built-in data type + Operations: cons, cdr, car, null?, null (car (cons a b)) = a (cdr (cons a b)) = b (null? null) = true (null? (cons a b)) = false Everything else is undefined + Behind the scenes, cons creates a pair of pointers. * Java + A standard class + A list is a collection + Collection operations; add, clear, remove, a lot ... + Operations: lots more * How do lists differ from other collections? + "Ordered" - Does this mean "Sorted?" no. It does mean that "1,3,4,5,8" is different from "1,3,4,8,5" + No random access ...? Whoops, they are in this implementation (but not efficiently). constructor What's a type? * Something predefined; you can also define your own * A collection of valid operations * A way to interpret bits in memory * A set of values Our goal: Look at lists first in the Scheme way and then extend them to something closer to the Java list interface. We are building a data structure called "Linked List"