This is the lecture note of CS61B - Lecture 6.
Two lectures ago, we built a naked recursive linked data structure —— IntList
. It works, but is hard to use.
So, in the previous lecture, we add an extra layer on the naked data structure and built a better linked list —— SLLit
. However, SLList has some limitations, one of them is inserting at the back of an SLList is much slower than adding at the front. This is because under the hood, to add an item at the end of the SLList, it needs to iterate through all of the items.
1 | public void addFirst(int x) { |
How could we modify our list data structure so that addLast is also fast?
DLList: Doubly Linked List
However, adding .last
and .prev
introduces a special case:
To avoid these, either:
- Add an additional
sentBack
sentinel at the end of the list. - Make your linked list circular (highly recommened for project 1), with a single sentinel in the middle.
You will implement your version of DLList in Project 1.
Generic Lists
Until now, our SLList
and DLList
only support Integers. To make our list more practical, one important task it to make it generic.
Java allows us to defer type selection until declaration.
1 | /** Generic SLList */ |
1 | public class SLListLauncher { |
Arrays
Try to understand the following code. I think it is easy for you to except the last line.
1 | int[] z = null; |
To understand array deeper, let’s take a look at 2-dimensional arrays in Java. Try to understand the following code.
1 | int[][] pascalsTriangle; |
This is the result:
Exercise: 2D Arrays
What will be the value of x[0][0] and w[0][0] when the code shown completes?
1 | int[][] x = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; |
🐹 Solution:
1 | x[0][0]: -1 |
Until now, we've seen how to harness a recursive class definition to build an expandable list, ie. the IntList
, the SLList
and the DLList
. In the next two lectures, we will transfer from linked data structure to arrays, and see how to harness arrays to build such a list, namely AList
.
See you next time. 🦄