100 likes | 171 Views
Class 3: Linked Lists. What is a linked list?. A linked list is an ordered series of ‘nodes’ Each node contains some data (‘soap’ or ‘garlic’) The data may also be numeric or other type (‘5’ or ‘true’). What is a pointer?. Think of the memory locations as an array
E N D
What is a linked list? • A linked list is an ordered series of ‘nodes’ • Each node contains some data (‘soap’ or ‘garlic’) • The data may also be numeric or other type (‘5’ or ‘true’) cis 335 Fall 2001 Barry Cohen
What is a pointer? • Think of the memory locations as an array • Each location has an index • Each location may contain a value • The pointer to a thing is the index in memory. • A pointer points to a particular type of thing (int, char, double ..) • Note the difference between the pointer and the thing being pointed to cis 335 Fall 2001 Barry Cohen
The ‘&’ and ‘*’ operators • ‘&’ is the ‘address of’ (reference) operator. You apply it to a thing. • ‘*’ is the ‘thing being pointed to’ (dereference) operator. You apply it to an address. • Example: int anInt = 5;int anIntPtr = &anInt;int anotherInt = *anIntPtr; • t/f? anInt == anotherInt; • t/f? &anInt = &anotherInt; cis 335 Fall 2001 Barry Cohen
The new and delete operators • thingPtr = new thing; reserves memory for a thing, and returns a pointer to it • delete thingPtr;frees the memory at location thingPtr. thingPtr continues to exist but doesn’t have any meaning • thingPtr = NULL;shows that thingPtr is no longer a valid pointer cis 335 Fall 2001 Barry Cohen
Array v. pointer implementation • Array: order of items is determined by index in array • Pointer: • each node contains a pointer to the next node • the list starts with a pointer to the first node, NULL if the list is empty • the pointer of the last node points to NULL cis 335 Fall 2001 Barry Cohen
Insert at head of linked list • Create new node • Assign thing value to it • Assign old list pointer as pointer value • Assign its value as the new list cis 335 Fall 2001 Barry Cohen
Find an item • Start at the beginning • Continue until you come to the item • Return a pointer to item cis 335 Fall 2001 Barry Cohen
Delete from middle of list • Find item • Make previous item point to next item • Free memory of the item cis 335 Fall 2001 Barry Cohen
Test for empty list • Does the listPtr point to NULL? cis 335 Fall 2001 Barry Cohen