Charlotte Curtis March 13, 2024
Textbook Sections 13.1
// Start the list Node *head = new Node; head->data = 1; // Add another element head->next = new Node; head->next->data = 2; head->next->next = NULL;
Textbook Chapter 13
In C++ syntax:
Node *current = head; while (current) { // or while (current != NULL) // do something with current->data current = current->next; }
current
NULL
Many algorithms, like printing a list, would be most useful as a function
What should be passed to the function? By value or by reference?
head
// by value void print(Node *head);
// by reference void insert(Node *&head, int value);
If Node *& is confusing, you can use a typedef:
Node *&
typedef
typedef Node * NodePtr; void insert(NodePtr &head, int value);
Write a function to calculate and return the length of a linked list.
Inputs: Head pointer (by value or by reference?)
Outputs: Length of list (what datatype?)
Say we defined an insertion function as:
void insert(Node *head, int value); // pass head by value
When testing with the value 5, this will work!
5
9
12
0
Pass-by-reference is only needed when head changes, but to keep your function general, you should assume that it might change
next
Node *current = head; while (current->next && current->next->data < value) { current = current->next; }
current->next
current->next->data
Node *prev = NULL; Node *current = head; while (current && current->data < value) { prev = current; current = current->next; }
prev
not NULL
For every linked list operation, think about the special cases!
What am I forgetting in the following code? Assume that a list of Nodes already exists with a pointer to head defined.
Node
head = temp;
delete temp;
temp = NULL
Node *temp = new Node; temp->data = 0; temp->next = head;
What is the following code doing? Again, assume head is defined.
Node *temp = new Node; temp->data = 5; temp->next = head->next; head->next = temp;
delete
Node *prev = NULL; Node *current = head; // Find the node to delete while (current && current->data != value) { prev = current; current = current->next; } prev->next = current->next; // Disconnect the node delete current; // Free the memory
What special cases do we need to consider?
tail
class
struct Node { int data; Node *next; Node *prev; };
Expanding on the previous example, consider the situation where:
struct Student { string name; int id; Course *courses; };
struct Course { string name; int number; Student *students; Instructor *instructor; };
struct Instructor { string name; Course *courses; };
COMP 2631 is all about various information structure
A class is a blueprint for creating objects, much like how a struct is a blueprint for creating data structures
struct
struct Student { string name; int id; };
class Student { string name; int number; void print(); };
A class is a type of object, just like int or string or Node
int
string
Member functions are accessed using . or -> just like member variables
.
->
Textbook Chapter 10.2-10.3