DEV Community

chase
chase

Posted on

A Short Intro to Doubly Linked Lists

Every single day, there is a programmer who is struggling with mountains of data and the proper way to organize it all. If only there were efficient ways to organize and sort all of this data so that they could access it and use it in a meaningful way... Lucky for us, computer scientists have figured out ways to do this using Data Structures. There are a lot of different types of data structures, but today I'm writing about a really simple one. Introducing, the doubly linked list (written in Ruby).

linked list code in ruby

Okay, okay, I'll admit that it doesn't really look like anything special right now, but allow me to explain what this data structure is. A doubly linked list is a structure made up of nodes.

node code

Each of these nodes contains a link to the previous node, the data stored within the current node, and a link to the next node. Please, have a look at this diagram I've made.

linked list diagram

My amazing art skills aside, this is what a very short doubly linked list would look like if we made it into a tangible object. The start of a linked list (also called the head) has a previous value of nil and the final node in the linked list (also called the tail) has a next value of nil. I will now show you a basic method for creating a new item in our linked list.

linked list push method

This function starts by creating a new Node object with whatever data you have being passed into it. If this linked list is empty, this brand new node becomes the head and the tail of our list. Now, if there are already nodes in the list, it will simply make your new node the tail of the list and increment the list length by one.

Now, I'm not going to go over all about traversing linked lists and other methods you can create in this blog post, but this has just been a very basic overview of a doubly linked list. Hopefully you're able to get some use out of this data structure.

Top comments (0)