Double Linked List Algorithm
For this week I decided to take a break from Python and work on an Algorithm in Java called Double Linked List. A DLL is a data structure used to sort data and retrieve data. It is very common in the work place and is a common data structure asked to get built in developer interviews. For this week I decided to work on 2 methods. The add first and the add last methods. In a double linked list there is always 2 nodes. The head and the tail. The head is where the data structure begins and the tail is where it ends. If there is no data in my list then they both point to null (empty). That is why in my empty constructor I initialized both the head and tail to point to null.
After we initialize the head and tail and make them both point to null I declared my first method which is add first. This is when you want to add a new piece of data to the beginning of your list. This is useful because if you know what data is in the beginning of your list you wont have to traverse through your entire list and is a lot faster to retrieve the data we want. First we make an object of the DLLNode class and put the data we want in it. This is what the E theData is in the parentheses. We give this the name of temp since it will only hold our data temporarily until we add it to our list. After that we add a condition that checks if our list is empty. If it is empty then obviously we just make it equal head and tail since there is no other data in our list. If it is not empty we attach temp to the head. This is done by calling temp.next and then connecting the previous part of head to temp. We finally move head to point at temp.
Our addLast method is similar to add first except we are dealing with tail instead of head. The first 3 lines of code are the same as addFirst since we always have to check if the list is empty to begin with. If it is not empty then we go straight to the end of our data structure We make tail.next equal temp. This connects the end of our data structure to the data in our temp variable. We then connect the back of our temp structure back to tail. Finally we make tail point to temp. I will be working on some other methods next week to see how we can add data in between the front and the end. This is a bit more tricky since we have to actually traverse through our list. It is not as easy as just going to the first node or the last node.
This is what we were looking for. I hope it's a little more challenging and fulfilling.
ReplyDeleteFor sure more challenging and honestly it's good that it's making me think more analytically about algorithms.
Delete