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