Documente Academic
Documente Profesional
Documente Cultură
Data Structures
For the rest of this course, we'll study different ways to store and organize data. Data structures
We learn different data structures, because each has its advantages and disadvantages. We'll template our data structures, so they can hold different types of data.
Erasing in a Vector
Dynamic arrays and vectors allocate sequential memory blocks. This is good for indexing. If the 10 block below is at address 1201, then the 40 block is at address 1204. But this is bad for inserting and erasing. If we want to erase the 20 block in the picture below, we have to shift all the elements over to the right.
10 20 30 40 10 30 40
This data structure is called a linked list. Each block is called a node. The pointers are called links. A node has two parts: the data and the link to the next node. The last node points to NULL, so we know where the list ends.
All we have to do is rearrange the pointers. Then we can safely delete the 20 block, freeing up that block for future use. Erasing is an O(1) operation! Inserting is just as easy!
So we need to ask which operations were going to be performing more often: accessing or changing the data.
The 3 Classes
Our linked list will be built on 3 inter-dependent classes. Node -- Stores one block of data. Private: T data, Node<T>* prev, Node<T>* next
prev data next
Iterator -- Marks our current position in the list. Private: Node<T>* position
We will also use the Iterator to mark the position of a node we want to erase or insert. When we erase a node, we will move the iterator to next position in list. myList.erase(iter); When we insert, we will insert the given value before the iterator position. myList.insert(iter, 25);
template <typename T> void Iterator<T>::forward() { position = position->next; } template <typename T> void Iterator<T>::backward() { position = position->prev; }
LinkedList Constructor
The default constructor just sets up an empty list. template <typename T> LinkedList<T>::LinkedList( ) { first = NULL; last = NULL; } The template allows us to store lists of ints, strings, etc. LinkedList<string> words; LinkedList<double> numbers; LinkedList<Matrix<double>> markovChains; Well discuss the destructor ~LinkedList() later, because it will use our erase() function.