Lecture 16: Linked lists

Mar 11, 2024  β”‚  Last updated Mar 8, 2024 by Charlotte Curtis

HTML Slides html β”‚ PDF Slides PDF

Where we left off

  • Dynamic memory allocation
  • Assignment 2
  • Midterm

Textbook Section 9.2

Time *t = new Time;
t->hour = 5;
do_something_with_time(t);
delete t;

Today’s topics

Textbook Sections 13.1

Another list structure? Why?

Linked lists overview

That Node structure looks funky

Yes, that’s a std::string - you can use them in assignment 3!

Pointers so far

So far we’ve learned how to:

Problem: we still don’t get “unlimited” memory because we need to associate a named variable with each memory address

Linked Lists

Concept demo time

Starting a linked list

Building the list

Adding to the front

Adding to the middle (inserting a node)

Adding to the middle is more expensive as it means traversing the list

emoji Linked list check-in 1/2

We can’t just dereference head + 1 to get the next item in the list because…

  1. The head pointer is a NULL pointer
  2. The linked list is not contiguous in memory
  3. The head pointer does not point to the first item in the list
  4. The memory allocated to head is not the size of a Node

emoji Linked list check-in 2/2

next needs to be a Node * and not a Node because…

  1. A struct cannot be a member of another struct
  2. All struct members must be pointers
  3. The memory would be allocated on the stack
  4. The memory allocation would be recursive

Basic list traversal

Traversing a list

In C++ syntax:

Node *current = head;
while (current) { // or while (current != NULL)
    // do something with current->data
    current = current->next;
}

Inserting a node

Basic approach:

Suppose the list already has the values 1 -> 5 -> 7 -> 10. We want to add the value 6 and keep the list sorted.

Handling special cases

We want to insert a node at the “proper” position, which may be:

Which of these need special handling? Next lecture we’ll look at some common approaches

Arrays vs Linked Lists

ArraysLinked Lists
Contains only dataContains data and pointers (more memory)
Fixed number of elementsVariable number of nodes
Minimum size is 1Minimum size is 0
Supports random accessMust traverse to find an element
Insertion/deletion requires shiftingInsertion/deletion is easy
Easiest insertion/deletion at the endEasiest insertion/deletion at the front
Need to know the length and fill levelEnd is marked by NULL

Coming up next

Textbook Chapter 13



Previous: Lecture 14: Dynamic Allocation and Midterm Review
Next: Lecture 16: More Linked lists