Browse Source

Add note on linked list

main
parent
commit
08c13c21fc
  1. 69
      notes/data-structures.org

69
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 <bits/stc++.h>
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

Loading…
Cancel
Save