Previous Lecture lect14 Next Lecture

lect14, Tue 02/26

Linked lists

Recap

Dynamic memory / the heap

It’s important to know the difference between the stack and the heap

The stack is where all local variables are stored - variables on the stack are destroyed automatically when they go out of scope

The heap is where all dynamic variables are stored - they are created with new and never go out of scope, but must be destroyed with the delete keyword

Example code:

int* p = new int;  //creates an integer on the heap and saves its address in p, created on the stack
delete p; //deallocates memory for that integer object. the value inside p is unchanged, but there is no object on the heap at that address

int size = 7; //size is an int created on the stack
int* a = new arr[size]; //creates an array on the heap of size 7, and saves the address of the first element in a.
delete [] a; //deallocates memory for the entire array

Lecture material

Intro to Linked lists

What are linked lists?

A linked list is a simple data structure that has nodes on the heap, and each node has a value and a pointer to the next node in the list.

A linked list itself has pointers to the first and last nodes.

Take a look at the written notes (link at the top of the page and on Piazza) to get a sense of how a linked list is represented in memory

Why use Linked lists?

Arrays are convenient because all elements are right next to each other in memory and can be quickly accessed.

But you cannot add new elements or quickly delete any - the size of an array is fixed, even of a dynamic one.

A linked list is not a dynamic array! A dynamic array is just an array on the heap - they are different from regular arrays because their size can be defined at runtime, and they differ from linked lists because once the size is defined, the array stays at that size (until you potentially delete and resize it using new []).

Arrays aren’t good for everything!

Structure of linked lists

Every Linked List has a head pointer to the first node of that list and a tail pointer to the last node.

Take a look at the example code from lecture, where a linked list is created and filled with values.

In an empty linked list, head and tail pointers are both NULL.

Traversing linked lists

It turns out you can traverse through linked lists pretty easily!

We will continue talking about Linked Lists in the next lectures.