From 596d863a25e2114b4b30a05edb4ea623381041ea Mon Sep 17 00:00:00 2001 From: Luke Else Date: Wed, 23 Nov 2022 20:44:21 +0000 Subject: [PATCH] #1 Added operator overload, [], to Linked List --- DataStructures/src/linkedlist.h | 8 +++++++- src/main.cpp | 1 + 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/DataStructures/src/linkedlist.h b/DataStructures/src/linkedlist.h index 9813bab..37cd6cb 100644 --- a/DataStructures/src/linkedlist.h +++ b/DataStructures/src/linkedlist.h @@ -9,7 +9,7 @@ namespace Datastructures { LinkedList(); LinkedList(T value); ~LinkedList(); - T operator[](int index); + T& operator[](int index); void append(T value); bool insert(T value, int index); bool remove(int index); @@ -43,6 +43,12 @@ namespace Datastructures { template LinkedList::~LinkedList() {} + template + T& LinkedList::operator[](int index) { + //Return the value from a given index. (Will return null pointer if out of range) + return this->getIndex(index)->value; + } + template void LinkedList::append(T value) { mCount++; diff --git a/src/main.cpp b/src/main.cpp index 6f54d42..07b0e36 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -7,6 +7,7 @@ int main() { list.append(200); list.insert(20, 2); std::cout << list.count() << std::endl; //3 + std::cout << list[0] << list[1] << list[2] << std::endl; //520020 list.remove(0); int x = list.find(10); std::cout << list.count() << std::endl; //2