From 08c13c21fc0ba9c3566ea5b7cb1a5844bbf506d1 Mon Sep 17 00:00:00 2001 From: Christopher James Hayward Date: Mon, 1 Feb 2021 09:39:19 -0500 Subject: [PATCH] Add note on linked list --- notes/data-structures.org | 69 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/notes/data-structures.org b/notes/data-structures.org index 5b7c183..2e7cb00 100644 --- a/notes/data-structures.org +++ b/notes/data-structures.org @@ -8,6 +8,75 @@ + Organization and management format + Forms the basis of abstract data types +* Linked List + +#+begin_export +(0 ->) (1 ->) (2 ->) (3 ->) (4 ->) +#+end_export + ++ Linear data structure ++ Elements linked using pointers ++ Not stored in a contiguous location + +Benefits to this approach are: + ++ Dynamic size ++ Ease of manipulation + +Drawbacks of this approach: + ++ Random access not allowed ++ Additional memory overhead ++ Not friendly to caching + +** Example + +Begin with the ~stc++~ header and the ~std~ namespace. + +#+begin_src cpp +#include +using namespace std; +#+end_src + +Define the data structure that will represent a single element (node) in the linked list. + +#+begin_src cpp +struct Node { + int data; + struct Node* next; + + Node(int d) { + this->data = d; + this->next = NULL; + } +}; +#+end_src + +Initialize a new linked list, with an initial value of =0=. + +#+begin_example +(0 ->) +#+end_example + +To illustrate our example we will create a simple linked list with three distinct nodes. The first step is creating our root node. + +#+begin_src cpp +Node* head = new Node(0); +#+end_src + +We can then append new items through the ~next~ field, which is a pointer to the next item in the list. When this value is ~NULL~ we have reached the end of the list. + +#+begin_src cpp +head->next = new Node(1); +head->next->next = new Node(2); +#+end_src + +This gives us the expected result of: + +#+begin_example +(0 ->) (1 ->) (2 ->) +#+end_example + * Binary Tree #+begin_example