#ifndef LINKEDLIST_H #define LINKEDLIST_H template struct LinkedListNode { T data; LinkedListNode* next; }; template class LLIterator { LinkedListNode *curr; public: LLIterator(LinkedListNode *s) : curr(s) {} // O(1) LLIterator operator++(){ // O(1) curr = curr->next; return *this; } bool operator!=(const LLIterator& other){ // O(1) return curr != other.curr; } T& operator*(){ // O(1) return (curr->data); } }; template class LinkedList { LinkedListNode *start = 0; public: void push_beginning(T data){ LinkedListNode *new_one = new LinkedListNode; new_one->next = start; new_one->data = data; start = new_one; } LLIterator begin(){ return LLIterator(start); } LLIterator end(){ return LLIterator(0); } void add_inorder(T data){ LinkedListNode *new_one = new LinkedListNode; new_one->next = start; new_one->data = data; if(!start || start->data > data){ start = new_one; return; } for(LinkedListNode *place = start; place; place = place->next){ if(!place->next || place->data < data){ new_one->next = place->next; place->next = new_one; break; } } } T index(size_t idx){ LinkedListNode *place = start; for(int i = 0; i < idx; i++){ // Runs once per list item, O(n) where n is the number of list items place = place->next; } return place->data; } void print(){ if(!start){ cout << "[]\n"; return; } cout << "["; LinkedListNode *place = start; while(place){ cout << place->data << ", "; place = place->next; } cout << "\b\b]\n"; } ~LinkedList(){ LinkedListNode *place = start; while(place){ LinkedListNode *todel = place; place = place->next; delete todel; } } template friend ostream& operator<<(ostream& output, LinkedList &list); }; template ostream& operator<<(ostream& output, LinkedList &list){ list.print(); return output; } #endif