<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Harveyroper on Medium]]></title>
        <description><![CDATA[Stories by Harveyroper on Medium]]></description>
        <link>https://medium.com/@harveyroper?source=rss-bb7a4add1caf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3IVQp5F5JJ9CUCUFj-dBpg.png</url>
            <title>Stories by Harveyroper on Medium</title>
            <link>https://medium.com/@harveyroper?source=rss-bb7a4add1caf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:18:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harveyroper/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An Overview of Data Structures and Their Implementation. Part 2 — Graphs and Trees]]></title>
            <link>https://medium.com/@harveyroper/an-overview-of-data-structures-and-their-implementation-part-2-graphs-and-trees-56a37cca606c?source=rss-bb7a4add1caf------2</link>
            <guid isPermaLink="false">https://medium.com/p/56a37cca606c</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Harveyroper]]></dc:creator>
            <pubDate>Thu, 14 Jul 2022 01:01:55 GMT</pubDate>
            <atom:updated>2022-07-14T01:01:55.006Z</atom:updated>
            <content:encoded><![CDATA[<h3>An Overview of Data Structures and Their Implementation. Part 2 — Graphs and Trees</h3><p>This is part two in a series on a survey of Data Structures in Computer Science, and their general implementation in programming languages.<a href="https://medium.com/@harveyroper/an-overview-of-data-structures-and-their-implementation-part-1-84d1f146464c"> Part 1 covered Arrays and Linked lists</a>. This part will cover two of the most fundamental non-linear structures: Trees and Graphs. The study of trees and graphs are deeply rooted in Mathematics, meaning they are incredibly rich fields of study, trees specifically have a family of data structures that all fall within the class of Tree, but serve specific and important purposes.</p><p>I’ve spent some time thinking about how best to deliver this article, compared to the first article, this article would quickly become cluttered if I said everything there is to say about graphs, and then begin talking about trees. This is because, crucially, unlike arrays and linked lists, which are <em>similar </em>structures to eachother, the set of all trees are fundamentally a subset of the set of all graphs. In other words, all trees are graphs, but not all graphs are trees. Therefore I am going to cover graphs first, and then look at trees, contrary to many courses on data structures, which look at trees first, I believe from a mathematical perspective this is a flawed premise.</p><h3>Introduction to Graphs</h3><p>Graphs precede the computer by about 87 years. They are the object of study in Graph Theory (shockingly), and was first formally studied in the 16th century by Euler when he was trying to solve the <a href="https://nrich.maths.org/2484">Königsberg Bridge Problem</a>.</p><p>Studying Graph Theory from a purely mathematical perspective is commonplace in the vast majority of Computer Science undergraduate degrees, and for good reason. Graphs are enormously powerful tools which have uses in several far removed areas of the field, from networking and search engines, to path finding, and even neural networks (in the simplest sense, a neural network IS a graph).</p><p>We consider graphs to be an object consisting of a collection of vertices, and edges that join them. It is usually very convenient to represent a graph well… graphically, and the first time most people encounter graphs is this way, here is an example graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b4mulG2ihUUwBTYMtZ9TNg.jpeg" /><figcaption>A graph. Source: Geeks for Geeks</figcaption></figure><p>The circles, conveniently labelled A-E are our vertices, and the lines that connect them are edges. Mathematicians like to formalise the definition of a graph using set theory so it is not uncommon to see the above graph be defined as so:</p><p><strong><em>Let G</em> be a graph G = (<em>V</em>, <em>E</em>) <br> V = {A,B,C,D,E}<br> E = {AB, AD, AE, BC, CE, CF, DE, DF}</strong></p><p>Note that the edge set is a collection of <em>pairs of vertices, </em>so AB is an ordered pair containing the vertices A and B.</p><p>Luckily for programmers, this definition of a graph is not essential information, however it is useful to know as it allows us to understand that any specialised kinds of graphs are only restrictions or expansions on this basic definition. Graphs are most simply a list of points, and another list of pairs of those points. We will soon come to look at more convenient methods of expression for graphs soon, so no more set theory for now.</p><p>You may now be imagining the large number of applications for this abstract representation of information. That is an important point too, graphs are purely a vector for information, data, etc, and relationships between.</p><p>Now that we have the basic definition of a graph, we can begin to look at some of the fundamental restrictions often placed on graphs which allow us to gain better insight into the relationship between nodes. Formally the graph pictured above could be defined as an <em>unweighted, undirected, cyclic, connected</em>, <em>simple graph. </em>This definition, currently, isn’t particularly useful as it is quite dense with terminology which we haven’t yet defined. However, this definition is very useful because it concretely describes the nature of the graph, and if I were to give anyone versed in some graph theory definitions this list of words, they could have a good go at drawing me some graph that had these restrictions imposed.</p><p>Lets try and unpack some of the common terms used to describe the kind of graph we are dealing with:</p><p><strong>Simple: </strong>A graph can be described as simple (named a simple graph) if and only if given that there is an edge which connects two vertices, then that edge is the <em>only </em>edge to connect those two vertices. NB: For those versed in a little set theory, you might immediately see how our initial set based definition of a graph becomes problematic. This doesn’t mean that non-simple graphs are complementary to set theory, they can still be defined with it, however that definition gets a little dense and is probably out of the scope of this article.</p><p><strong>Connected: </strong>One major misconception many people first encountering graphs have, I certainly did is the idea that every node in a graph has to be linked by an edge. This is fundamentally untrue, for example this is a perfectly fine graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*HwlH3UHi1F97ydHODA44sg.png" /><figcaption>A Disconnected Graph. <a href="https://algorithms.tutorialhorizon.com/breadth-first-search-in-disconnected-graph/">Source</a></figcaption></figure><p>Letting the vertex set be {0,1,2,3,4,5,6} we can see that these look like two graphs put next to each other, however it is perfectly fine to consider the entire system as one graph. Naturally therefore, we can consider a graph to be connected if and only if this assumption is true. Formally we might say that for any arbitrary vertices <strong>v, w </strong>in the vertex set <strong>V, </strong>there exists some path <strong>p </strong>which connects<strong> v </strong>and <strong>w</strong>.</p><p>In the figure above, Graph Theorists describe the two sections as being <em>connected components </em>of G. This gives us another definition, that is a graph G is connected if and only if it has one connected component.</p><p><strong>(Un)Directed: </strong>In understanding the concept of direction in a graph, it is useful to imagine someone (it could even be you!) standing on one vertex, and that person will walk between vertices through the edges. If a graph is undirected, as all of the examples so far have been, then the person is free to walk from one vertex to another, and then back via the same edge. Naturally then a directed graph enforces a direction for the edges, ie A is connected to B, but B is not connected to A. You might even imagine a map of roads, consisting of one way streets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inHO5G4DOy6VJ9D0O79vfw.png" /><figcaption>A Directed Graph</figcaption></figure><p>Above we see visual representation of a directed graph. It is commonplace to draw the edges as arrows to indicate the direction of travel permitted between vertices. Observe also that we have two arrows between vertices 3 and 4, telling us that it is permitted for two neighbouring vertices to be connected to each other. Consider for yourself whether this graph is simple or not.</p><p><strong>(Un)Weighted: </strong>The easiest way to understand the idea of a weighted graph is to picture the vertices of a graph as cities, and the edges the roads that connect them. Of course cities are a measurable distance apart from each other, and indeed some cities which may be directly connected by a road will be closer to each other than other cities. Therefore it often makes sense to attribute the edges of a graph with weight. Many areas of computer science utilise this, often giving it a couple of different names include: weight, cost, distance, value, preference, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*451iUsFZG6k2ph8NkxjPqQ.png" /><figcaption>A Weighted, Directed Graph</figcaption></figure><p>This above graph shows the idea of a weighted graph, which is also directed.</p><p><strong>(A)Cyclic: </strong>The last key definition we have for graphs is whether a graph is cyclic or acyclic. Cyclic coming from the word cycle. We say that a graph has a cycle if there exists a path <strong>p </strong>from a vertex <strong>v </strong>back to itself, where <strong>p</strong> does not traverse through any edge more than once. A graph that is acyclic does not have such a path. Alternatively sometimes we define a cycle as there being more than one unique path between two vertices in a graph, and so conversely an acyclic graph, if there exists a path between two vertices, that such a path is unique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*t0slLEYUnEYbxySrObmJrQ.png" /><figcaption>Cyclic vs Acyclic Graphs</figcaption></figure><p>Take some time to consider why the graph on the right is infact NOT cyclic. Note that the above graphs are directed!</p><h4>Enough Maths for now</h4><p>So far I have spent all of this article far removed from programming at all, and for the more hands on programmer this might be frustrating, but for now we’ve covered enough graph theory to get us by. Note that graph theory is an incredibly rich field of study, with countless more definitions that I have benevolently omitted from this article, if the past 10 minutes of reading have been interesting to you, Introduction to Discrete Mathematics by Rosen is a fantastic resource for learning Graph Theory, as well as other areas of discrete maths, of which graph theory is a major component of.</p><p><strong>Methods of implementation for graphs:</strong></p><p>Up until now we have discussed two representations of a graph, neither of which are particularly handy if you’re trying to write any software. There are two conventional approaches for implementation a graph structure within a programming language. Those being an adjacency list, and an adjacency matrix.</p><p><strong>Adjacency Lists: </strong>Imagine we have a structure for a node of a graph, as we had looked at before, a linked list has two required pieces of information, a payload, and the next node in the list. For graphs, instead of having just one, we may choose to have a list of neighbouring vertices, some pseudocode might look like:</p><pre>structure Node {<br> <br>    Type payload;  <br>    List&lt;Node&gt; neighbours;</pre><pre>}</pre><p>There are a few methods for implementing the adjacency list approach, however for brevity I wont discuss the specifics of implementation here.</p><p><strong>Adjacency Matrix:</strong></p><p>This method is arguably a less common approach but does have significant benefits over the adjacency list approach. An adjacency matrix takes the idea of a mathematical matrix, where each entry in the matrix denotes whether two notes are connected, in an unweighted undirected matrix, this would be a symmetric binary matrix (dont worry if you dont know what that means)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*Xrd8CZ9Q94-_hW3njtPJcA.jpeg" /><figcaption>Source GeeksForGeeks</figcaption></figure><p>Above is an example of a graph and its corresponding adjacency matrix representation. You can see that all nodes that are connected to each other appear as a 1 in the matrix, otherwise there is a zero. Note also that there are no loops in this graph, so no nodes are connected to themselves.</p><p>There are a number of reasons to use an adjacency matrix over an adjacency list including:</p><ul><li>Adding, removing, and checking for edges is very efficient.</li><li>Calculations can be done efficiently on the GPU because of matrix representation.</li><li>Matrix operations give insights into the nature of the graph (Linear algebra applications)</li></ul><p>There are however cons, the biggest one being that, as you can see, it uses up a lot more memory than an adjacency list, requiring space which scales with the number of vertices squared.</p><p>We know that a matrix can be represented as a 2D array such as:</p><pre>int matrix[10][10]; </pre><p>Consider however challenges that arise if you wish to have an array of dynamic size, either dynamic memory allocation must be used or other techniques may require implementation.</p><h4><strong>Important algorithms for graphs:</strong></h4><p>There is not much use for implementing graphs into a programming language if there is not a good use for them, other than that they look cool. It is often important for us to be able to perform actions onto our graph, perhaps to learn things about it, or more importantly things about the information the graph is representing.</p><p>Classically the example that is given is path finding. Picture a maze, with yourself in it. You have a map of the maze and you would rather like to get out before the minotaur decides your her lunch. By representing the maze as a graph, there are algorithms which can determine either the fastest path to get out of the maze, or one thats pretty close.</p><p><strong>Dijkstra’s Shortest Path Algorithm: </strong>A legend in the computer science world, Dijkstra’s name is perhaps most widely known to programmers for an algorithm he designed that is so important is it often just referred to as his algorithm. Dijkstra’s will guarantee the shortest path within a weighted graph (Note that this can work for an unweighted graph if you consider every edge to have equal weight). Is is fantastically useful for this purpose and unless you happen to have (or know anyone that has) solved P vs NP lately, its the best we have for determining the shortest path from A to B in a graph.I think a full explanation of how the algorithm works is a little out of the scope of this article, however I believe its existence is worth mentioning and I fully suggest you go about learning how it works in your own time.</p><p>The only trouble with the algorithm is, its bloody slow, like really really slow. The second your graph gets a bit big, the algorithm really starts to drag which is a problem because normally we like working with large data sets.</p><p><strong>A different approach: </strong>For that computer scientists came up with a clever approach. They made a “worse” algorithm. Heavy emphasis on the air quotes there. The algorithm in question was invented in the 60s, and goes by the name A* (read A star). A* works on the principle that if we have a really big maze, or a really big graph more pertinently, sometimes the exact best possible path is not worth having for the drastically increased amount of time it will take to find it. A* is what we call a heuristic algorithm, in the sense that it employs one to try and figure out what is roughly the best approach at the time and goes with that.</p><p>A* is typically what is used more widely because it is a far more efficient algorithm, even if it is a worse path finder than Dijkstras. This notion of theoretical performance, vs what actually is more useful is a theme that occurs time and time again in computer science, and I believe this example is one of the best introductions to it.</p><p>These two examples serve as a brief introduction into the world of graph based algorithms, I highly recommend looking further into them as practising these algorithms, among others such as: Depth First Search, Breadth First Search, Minimum Spanning Tree, and Delaunay Triangulation, to name a few, are fantastic ways to become an excellently skilled programmer in data structures and algorithms.</p><h3>Introduction to Trees</h3><p>So we have now covered graphs in a good amount of detail to have a familiarity with what they are, how they function, and perhaps the kinds of problems we can solve with them.</p><p>Within many graph theory courses, the topic of trees is mentioned, this is because they are incredibly useful mathematical objects.</p><p>Crucially, a tree IS a graph, while in computer science the two data structures are often used for widely different purposes, and for that reason it can be easy to be tricked into thinking they are different things (much how stacks and queues are considered totally unrelated objects). Any graph is called a tree if it can be considered: acyclic, connected and undirected, all three of those definitions are covered above in the graph section if you need a reminder.</p><p>These conditions provide us with certain predictable behaviour for trees which come up a lot in graph theory, however for this article I am not going to focus on that too much.</p><p>Critically therefore if you wish to implement a general tree into a programming language, it is necessary and sufficient to implement a graph. There are then algorithms for checking whether said graph is a tree.</p><h4>Binary Trees</h4><p>Since we learnt that trees effectively are graphs, we shall look at a subcategory of trees, named the binary tree. Binary trees are incredibly useful to computer scientists for representing data, and are perhaps one of the most widely used data structures ever.</p><p>A binary tree gets it’s name by imposing the restriction that each node in the tree have no more that two child nodes. Technically each node in a binary tree has a maximum degree of 3 (maximum of 3 neighbours) however, we consider each node to have one parent node, and up to two child nodes. Therefore the tree structure creates a hierarchy, and it is common to draw the trees to represent this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*kEGFGUPw3YfcPiMuT74nzA.png" /><figcaption>A Binary Tree: Source Wikipedia</figcaption></figure><p>Pictured above is an example of a binary tree. We can see that while some nodes do have 3 neighbours, no node had more than two child nodes.</p><p>Nodes which have no child nodes are called leaf nodes (ie the leaves of a tree) The node which does not have a parent node is called the root node.</p><p>It may possibly be beneficial to picture this representation of the tree as being upside down, with the roots at the top and the leaves at the bottom. Whatever works for you.</p><p>Binary trees are so incredibly useful in computer science it is difficult to overstate their importance. They have uses in: decision making, expression evaluation, sorting, searching, data compression and more. Binary trees also serve as the basic structure type for even more specialised trees.</p><p>Binary trees are beautifully simple to implement too. They are only slightly more complex than the linked list, and if one is able to implement a linked list they are certainly able to implement a binary tree. Let’s take a look at one implementation:</p><pre>structure binaryTreeNode {</pre><pre>    type payload;<br>    binaryTreeNode* parent;<br>    binaryTreeNode* leftChild;<br>    binaryTreeNode* rightChild;<br>}</pre><p>Thats really it, each node is able to carry some information, and then pointers to its parent and respective child nodes. Some implementation would have the child nodes stored as an array and accessed via pointer arithmetic, but this approach also works and is more explicit.</p><p>Generally, binary trees have a selection, insertion, and deletion time complexity of O(n), which isn’t bad! However there are methods of arranging our tree to create new kinds of trees that allow us to search for elements in much faster than linear time (logarithmic). Something called a binary <em>search </em>tree allows for this, and it is a specific method of ordering the elements in our tree so that we can follow an algorithm to find them.</p><p><strong>Note: </strong>The brevity of this section on trees is not something I haven’t noticed, however over the course of writing this article I realise that in order to cover everything I believe it is important to know to have a strong grip on trees, the more exotic flavours of trees would require their own article, things such as: BSTs, AVL Trees, Red-Black Trees, Splay Trees, Heaps, Tries, Treaps, B-Trees. To name pretty much all of the big ones.</p><h3>Conclusion</h3><p>That concludes this section of the introduction to Graphs and Trees in a wider series of articles on data structures. In writing this article I feel it will be necessary to revisit trees to look at some of the more advanced flavours of the data structures, eventually I will do this in a future part of this series. I hope this article has been informative and maybe even a little entertaining. Thanks for reading.</p><p>Harvey</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56a37cca606c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An overview of Data Structures and their implementation. Part 1 — Arrays and Linked Lists]]></title>
            <link>https://medium.com/@harveyroper/an-overview-of-data-structures-and-their-implementation-part-1-84d1f146464c?source=rss-bb7a4add1caf------2</link>
            <guid isPermaLink="false">https://medium.com/p/84d1f146464c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Harveyroper]]></dc:creator>
            <pubDate>Thu, 07 Jul 2022 00:04:35 GMT</pubDate>
            <atom:updated>2022-07-20T16:51:19.635Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*biJ3zXEuRvimNdv-q9kHaQ.png" /></figure><p>Hi there! This article serves as a survey of my understanding of data structures, including the classic examples from computer science (Linked Lists, Trees etc) as we as hopefully in later parts an exploration into representation of mathematical structures such as groups, vector spaces, fields etc and methods of implementation in programming languages.</p><p>I will attempt to mostly stick with C style pseudocode for the sake of generality, however where necessary I may take advantage of the rich standard library of Java to ease the process in places.</p><h4>What is a Data Structure. Why Care?</h4><p>Data structures are generally something that is only talked about in computer science, in pure mathematics, there is no need for the notion of a linked list, or an array. Mathematics has the privilege of infinity, ideas such as sets allow for an unordered collection of any object, it can be extended to multisets, and relations and functions allow for the addition of direction. Or more simply we also have tuples, which are fixed ordered collections of objects, meaning that is it fine to collect objects and manipulate them, and never worry about ‘how’ we might physically do that. In programming however, we are always limited to a fixed memory space, and must assume that it takes time to access information. Therefore various techniques to arrange this data must be studied, so that we can more efficiently access and edit the data we wish to hold. Data structures study ways in which we can… structure data.</p><h3><strong>Arrays</strong></h3><p>An array is the most fundamental data structure, perhaps a variable is more fundamental, however classically we do not consider them to be data structures. It could be argued, from a set theoretic perspective that indeed if all mathematical objects are sets, then (and C permits this in some sense with array pointer duality) all objects in programming, are arrays, variables perhaps some equivalent of singleton sets.</p><pre>a<br>b = 10<br>c = [1,2,3]<br>d = [[1,2,3],[4,5,6],[7,8,9]]<br>e = [b,c,d]</pre><p>It’s a nice idea to consider arrays as being very akin to sets, however they are not analogous to eachother. Arrays are necessarily ordered, and generally fixed length (They are immutable). They also can contain identical elements twice. eg: [1,1,2,3]<br><em>NB: Python throws a spanner in the works here because lists, arrays, and tuples (though often confused) are necessarily different objects, with some subtle but important differences.</em></p><p>One further difference between mathematical sets and and an array is the standard enforcement of Type for arrays. For example we might have an array of integers, and the inclusion of a floating point number would be invalid.</p><p>Anyway, none of that is really relevant when studying data structures, however I do think there is something interesting about the parallels and differences between the most basic collection of objects in mathematics and programming.</p><h4>How do arrays really work?</h4><p>Arrays in the most primitive sense are simply a memory buffer. It asks the operating system to set aside a discrete amount of contiguous memory space, which you can then fill with whatever you want! Breaking that down a little, contiguous means that the memory registers allocated will be located one after the other in memory with nothing inbetween. If we created an array of characters (assume a char is one byte), length 4. Somewhere in memory there will be four registers which for the runtime of the program will only contain what you put in them. The benefit of contiguous storage is O(1) lookup for any element of the array if you know the index of that element. In case the reason for that isn’t immediately obvious sample the following C code:</p><pre>int array[] = {1,2,3,4,5}; //Array of integers<br>int* p = &amp;array; //Pointer to the start of the array<br>int b;<br>b = *p //b = 1<br>b = *(p+2) //b = 3</pre><p>Pointer arithmetic allows us to calculate the address of any element of the array, and then gets its value by dereferencing, by simply adding to the address of the start of the array.</p><p>The drawback of contiguous memory allocation is that you only have as much space as you allocate, you cant make the array bigger, because the registers located after your array will most likely be in use, and even if they aren’t, there is no guarantee you can just access that memory space, in fact it is fundamentally unsafe for the operating system to let a programmer do so. There are a number of exploits, the most basic of which being the <a href="https://en.wikipedia.org/wiki/Buffer_overflow">buffer overflow attack</a>, which surround this.</p><p>Therefore we require a way to collect items in such a way that we could continue to add more items to our collection, and from here we begin to look at more complex abstract data structures. The simplest of which is the Linked List.</p><h3>Linked Lists:</h3><figure><img alt="A diagram of a linked list" src="https://cdn-images-1.medium.com/max/759/1*6ReSYwX-z-n4jWPCRSxqBw.png" /><figcaption>Source: geeksforgeeks.org</figcaption></figure><p>One of the first times someone explained a Linked List to me, they used the analogy of a train, containing multiple cars. One can imagine a series of carriages connected together, as trains often are. This can give the illusion of the train being one contiguous entity, however obviously it is not, and if it were necessary to add more carriages, then it would be possible to do so.</p><p>Likewise, as trains are made up of individual cars, a linked list consists of nodes. Nodes themselves contain at the very least two pieces of information, the Data (or Payload in cooler terms) and the pointer to the next node. In this sense the definition of a linked list is beautifully simple, two pieces of information are required, value and a pointer.</p><p>Above describes what we’d call a singly linked list, named so because each node is linked in only one direction, this had the effect that you can only traverse the list in one direction. This usually might be quite annoying, since unless you store a permanent reference to the head (First node) of the linked list (A good idea anyway), you will lost the entries in the list that exist before the one you are currently at. For this we create a <em>doubly </em>linked list, where each node contains data, and a pointer to both the previous node and the next node in the list. Handy.</p><p>In a linear linked list, that is a doubly or singly linked list we consider the next pointer of the tail node, and the previous pointer (for doubly linked lists) of the head node to point to NULL. A nod to the idea that it is the end of the list, and therefore points to nothing, however to avoid having to create structures to accommodate these special nodes, we set their pointers to null instead.</p><p>Pseucode of a singly linked list:</p><pre>structure LinkedListNode{</pre><pre>    Type Payload<br>    LinkedListNode* next //* means a pointer</pre><pre>}</pre><p>Thats it! The simplicity of implementation makes linked lists very easy to work with. In some sense, there is a recursive nature to the definition of a linked list node, since its definition contains itself, this can be confusing but fear not, the compiler knows what to do.</p><p>Note: There is another kind of linked list, which in truth I am aware of however I have never really needed to use, this is a circular linked list. A circular linked list very simply is one in which the tail node of the list points to the head node, allowing you to traverse through the list in a circular manner. This has a few implications which I recommend thinking about, a few include: the removal of the issue of losing entries in singly linked lists, small improvements in traversal times, as well as possibly some applications to modular arithmetic. It naturally follows that doubly circular linked lists are also a thing (a doubly linked list that is also circluar).</p><h4>Performance of a linked list:</h4><p>Unlike arrays, which have a constant lookup time, linked list have a linear lookup time, O(n). This is because if you wish to get the data from the nth node in the list, you must traverse through all n-1 nodes before it to get to it.</p><p>This means that there is no universally good decision when it comes to using an array or a linked list, it is the job of a good programmer to judiciously decide which is the best for their purposes.</p><h4>Stacks and Queues:</h4><p>You may be familiar with the terms stack and queue, you may even have a good idea how they operate too. If you were like me and struggled to understand the difference between a stack, queue, and a linked list I’ll briefly describe here. A stack is any kind of list which operates in a LIFO (last in first out) scheme. This means that you can only access the piece of data which is at the start of the list, or in better terms, on the top of the stack. You can imagine a stack of cards, in which you can only remove the card from the top of the pile. In programming this means that you have to remove the item on the top of the list to get the next one. This paradigm is useful in many areas of computing, consider algorithms such as recursive backtracking, or anything which requires some kind of history of action, the lower on the stack the older the element. Stacks are also used in the flow of programs in which function calls, recursion, iteration etc are used. For fun, the website Stack Overflow gets its name from the programming error in which the stack allocated to a program gets full and more data is added to it, hence stack <em>overflow.</em></p><p>A queue is essentially the opposite, it operates in a FIFO (First in first out) scheme, and as you may be able to guess works based on the real world idea of a queue. Imagine lining up at the bank, whoever gets there first gets served first, I can imagine it is not difficult to think of many ways a queue is a useful data structure.</p><p>Now importantly, a linked list is a more abstract idea, stacks and queues are restrictions imposed on the general idea of a linked list to enforce certain behaviour. A linked list is a method of implementation of both of these things. Note that it is not the only way, commonly a queue is made using a primitive array which we know imposes a discrete size. If we knew that a queue would never have more that 10 elements, implementation with a linked list might not be the best approach.</p><p>Stacks and queues require two methods each to be fully implemented. The two methods essentially perform the same thing but classically have different names. Stacks feature a push and a pop method, in which elements are pushed onto the stack, and popped off. Queues have enqueue and dequeue, performing the equivalent action.</p><h4>Operations on linked lists:</h4><p>Discussions surrounding algorithms associated with arrays and linked lists are outside of the scope of this article, things like searching and sorting algorithms, among a sea of others. They’re something I would love to cover in another article. However there are certain operations which are so useful and fundamental to these data structures, it feels important to mention.</p><p>These include: Reversing a linked list, rotating a linked list, and insertion and deletion at a given index.</p><p>Reversing a linked list is the process of making each node point to the previous node, instead of the next one, effectively flipping the order. ie: <br>1-&gt; 2-&gt; 3-&gt;4-&gt;5 becomes 5-&gt;4-&gt;3-&gt;2-&gt;1.</p><p>Pseudocode code might look something like:</p><pre>function reverse(node* head){<br>    prev = NULL<br>    curr = head<br>    next = curr.next</pre><pre>    while(current.next != NULL){</pre><pre>        next = current.next <br>        // NB Implementing in C would require the -&gt; operator</pre><pre>        current.next = prev<br>        prev = current<br>        current = next<br>    }<br>    head = prev<br>    return head</pre><pre>}</pre><p><strong>Round up notes:</strong> So far we have covered primitive arrays and Linked Lists. For the sake of brevity in this article, I will cover non linear data structures (Trees, graphs, hash maps, etc) in a part 2. However, it is important to stress that there are many more flavours of linear data structures, such as dynamic arrays, associative arrays, unrolled linked lists, skip lists, and multi level linked lists. I do encourage you to look into these if you are interested. <a href="https://www.geeksforgeeks.org/skip-list/?ref=lbp">This link is an excellent resource </a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84d1f146464c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>