This preview shows pages 1–3. Sign up to view the full content.

1 Lecture 12: More Linked Lists PIC 10B Todd Wittman Recall : The 3 Classes s Our linked list will be built on 3 inter-dependent classes. s Node -- Stores one block of data. Private : T data, Node<T>* prev, Node<T>* next s LinkedList -- A list of nodes. Private : Node<T>* first, Node<T>* last s Iterator -- Marks our current position in the list. Private : Node<T>* position Functions : forward(); backward(); T get(); bool isNull(); data next prev 10 20 30 NULL NULL first last position

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Erasing a Node s Suppose we want to erase the block marked by iter: erase(iter); s First get a pointer to that block: Node<T>* pos = iter.position; 10 20 30 40 NULL NULL s We first need to rearrange the pointers around the 20. 10 20 30 40 NULL NULL s Then we can safely delete the 20 block: delete pos; s Note we have to be careful if 20 is first or last block. s When done, move iterator position to the next block (30). pos (pos->prev)->next = pos->next; (pos->next)->prev = pos->prev; pos Erasing a Node template <typename T> Node<T>* pos = iter.position; iter.forward(); if (pos == first) first = pos->next; else (pos->prev)->next = pos->next; if (pos == last) last = pos->prev; else (pos->next)->prev = pos->prev; delete pos; return; } pos points to Node move iterator to next Node Check if we're erasing first node. Set next pointer of the node before this one. Check if we're erasing last node.
This is the end of the preview. Sign up to access the rest of the document.