CS 225
Data Structures
Se
- Sept. 20
20 – Ar Array Li Lists - St Stac acks and and Que ueue ues
G G Carl Evans
CS 225 Data Structures Se Sept. 20 20 Ar Array Li Lists - St - - PowerPoint PPT Presentation
CS 225 Data Structures Se Sept. 20 20 Ar Array Li Lists - St Stac acks and and Que ueue ues G G Carl Evans List.h 1 #pragma once 2 3 template <typename T> 4 class List { 5 public: /* ... */ 28 private: 29
Data Structures
Se
20 – Ar Array Li Lists - St Stac acks and and Que ueue ues
G G Carl Evans
#pragma once template <typename T> class List { public: /* ... */ private: };
List.h
1 2 3 4 5 … 28 29 30 31 32 33
C S 2 2 5 [0] [1] [2] [3] [4]
C S 2 2 5 [0] [1] [2] [3] [4]
insertAtFront:
Singly Linked List Array Insert/Remove at front Insert at given element Remove at given element Insert at arbitrary location Remove at arbitrary location
#pragma once #include <vector> template <typename T> class Stack { public: void push(T & t); T & pop(); bool isEmpty(); private: std::vector<T> list_; }; #include "Stack.hpp"
Stack.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
template <typename T> void Stack<T>::push(const T & t) { list_.push_back(t); } template <typename T> const T & Stack<T>::pop() { const T & data = list_.back(); list_.pop_back(); return data; } 3 4 5 6 7 8 9 10 11 12 13
class ListNode { public: T & data; ListNode * next; …
1. 2. 3.
class ListNode { public: T * data; … class ListNode { public: T data; …
Storage by Reference Storage by Pointer Storage by Value Who manages the lifecycle
Is it possible for the data structure to store NULL? If the data is manipulated by user code while in our data structure, is the change reflected in our data structure? Is it possible to store literals? Speed
Sphere s; myStack.push(s); 1 2 Sphere s; myStack.push(&s); 1 2
Storage by reference: Storage by pointer: Storage by value:
Sphere s; myStack.push(s); 1 2
class ListNode { public: T & data; ListNode * next; ListNode(T & data) : data(data), next(NULL) { } }; T ** arr;
Storage by reference: Storage by pointer:
T * arr;
Storage by value:
Sphere s(1); myStack.push(s); s.setRadius(42); Sphere r = myStack.pop(); // What is r’s radius? 1 2 3 4 5 6 7