1. Home
  2. Explore
  3. Computer Science
  4. Data Structures Fundamentals

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Data Structures Fundamentals

Transcript

In these first few videos, I want to lay the foundation of some core concepts you will need throughout these video tutorials. Let's get started with the basics. So what is a data structure? one definition that I really like is a data structure is a way of organizing data so that it can be used efficiently. And that's all data structure really is it is a way of organizing data in some fashion so that later on it can be accessed, queried,

or perhaps even updated quickly and easily. So why data structures? Why are they important? Well, they are essential ingredients in creating fast and powerful algorithms. Another good reason might be that they help us manage and organize our data in a very natural way. And this last point, is more of my own making. And it's that it makes code cleaner and easier to understand. As a side note, one of the major distinctions that I have noticed from

bad mediocre to excellent programmers is that the ones who really excel are the ones who fundamentally understand how and when to use the appropriate data structure for the task they're trying to finish. data structures can make the difference between having an okay product and an outstanding one. It's no wonder that every computer science undergraduate student is required to take a course in data structures. It is strange that before we even

begin talking about data structures that we need to talk about the abstraction of data structures. What I'm talking about is the concept of an abstract data type. What is an abstracted type and how does it differ from a data structure? Well, the answer is that an abstract data type is an abstraction of a data structure, which provides only the interface to which that data structure must adhere to. The interface does not give any specific details on how

a specific data structure should be implemented, or in what programming language. One particular example I like to give is to suppose that your abstract data type is for a mode of transportation to get from point A to point B. Well, as we both know, there are many modes of transportation to get from one place to another. So which one do you choose? some specific modes of transportation might be walking or biking, perhaps even taking a train and so on, these

specific modes of transportation would be analogous to the data structures themselves. We want to get from one place to another through some mode of transportation, that was our abstract data type. How did we do that? Exactly? Well, that is the data structure. Here are some examples of abstract data types on the left, and some possible underlying implementation on the right hand side. As you can see, a list can be implemented in two ways. You can

have a dynamic array or a linked list. They both provide ways of adding, removing and indexing elements in the list. Next, we have a queue and the map abstract data types, which themselves can be implemented in a variety of ways. Notice that under the implementation for a queue, I put a stack based queue because yes, you can have a queue, which is implemented using only stacks. This may not be the most efficient way of implementing a queue. But

it does work and it is possible. The point here is that the abstract data type only defines how a data structure should behave, and what methods it should have, but not the details surrounding how those methods are implemented. Alright, now that we were done with abstract data types, we need to have a quick look at the wild world of computational complexity, to understand the performance that our data structures are providing. So as programmers,

we often find ourselves asking the same two questions over and over and over again. That is, how much time does this algorithm need to finish and also how much space Does this algorithm need for my computation. So, if your program takes a lifetime of the universe to finish, then it's no good. Similarly, if your program runs in constant time, but requires a space equal to the sum of all the bytes of all the files on the internet, internet,

your algorithm is also useless. So just standardize a way of talking about how much time and how much space is required for an algorithm to run. theoretical computer scientists have invented big O notation, amongst other things like big theta, big omega, and so on. But we're interested in Big O because it tells us about the worst case. Big O notation only cares about the worst case. So if your algorithm sorts numbers, imagine the input is the worst

possible arrangement of numbers for your particular sorting algorithm. Or, as a concrete example, suppose you have an unordered list of unique numbers, and you're searching for the number seven, or the position where seven occurs in your list. And the worst case isn't one seven, that is at the beginning. Or in the middle of the list, it's one seven is the very last element of the list. for that particular example, the time complexity would be linear

with respect to the number of elements in the size view list. Because you have to traverse every single element until you find seven. The same concept applies to space, you can just consider the worst possible amount of space your algorithm is going to need for that particular input. There's also the fact that big O really only cares about what happens when your input becomes arbitrarily large. We're not interested in what happens when

the input is small. For this reason, you'll see that we ignore things like constants and multiplicative factors. So in our big O notation, you'll often see these coming up. Again, again, again. So to clarify one thing, when I say n, n is usually always want to be the input size coming into your algorithm, there's always going to be some limitation of size n. So constant time referred to as a one wrapped around a big O. If your algorithm case in logarithmic amount of time to finish,

we say that's big O of a log event. If it's linear, then we just say n, if it takes like quadratic time or cubic time, then we say that's n raised to that power, it's exponential. Usually, this is going to be something like two to the n three, the N, N number be greater than one to the n. And then we also have n factorial. But we also have things in between these like square root of n log log of n, n to the fifth and so on. Actually, almost

any mathematical expression containing n can be wrapped around a big O. And is big O notation valid. Now, we want to talk about some properties of Big O. So to reiterate what we just saw in the last two slides, Big O only really cares about what happens when input becomes really big. So we're not interested when n is small, only what happens when n goes to infinity. So this is how and why we get the first two properties.

The first that we can simply remove constant values added to our big O notation. Because if you're adding a constant to infinity, well, let's just infinity, or if you're multiplying a constant by infinity, yeah, that's still infinity. So we can ignore constants. But of course, this is all theoretical. In the real world. If your constant is of size, 2 billion, probably, that's going to have a substantial impact on the running time of your algorithm.

However, let us look at a function f, which I've defined over some input size. And if f of n is seven log of n cubed plus 15 n squared plus two n q plus eight. Well, big O of f of n is just n cubed, because n cubed is the biggest, most dominant term in This function. All right, now let's look at some concrete examples of how big O is used. So both of the following run in constant time with respect to the input size, and because they don't depend on n at all.

So on the left, when we're just adding or doing some mathematical formula, yes, that's constant time. And on the right, okay, we're doing a loop, but the loop itself doesn't depend on n. So it runs also in a constant amount of time. So as our input size gets arbitrarily large, well, that loop is still going to run in the same amount of time regardless. Now let's look at a linear example. So both the following actually run in

linear time with respect to the input size, and because we do a constant amount of work, and times. So on the left, we're incrementing, the counter AI by one each time. So f of n is and, and clearly, when we wrap this in a big go get a big O of n. On the right, a little bit more complicated, we're not incrementing by one, we're incrementing by three, so we're going to finish that loop three times faster. So f of n is n over three. So our second example

is two algorithms that run in quadratic time. So the first one seems obvious, we do n work at times. So n times as big O of n squared. But observe the second one, I changed the zero with an eye. So pause the video and try to figure out maybe why that's big O of n squared. Okay, let's go over the solution. So first, just focus on the second loop. The first loop isn't as important. So since I go from zero to n, the amount of looping done

is going to be directly related to what AI is, and remember is changing from the outer loop. So if we fix AI to be zero, we do n work. We fix it one, we do n minus one work. If we fix it, too, we do n minus two work and excetera. So the question then becomes what is n plus n minus one plus n minus two plus n minus three and so on? Well, this is a well known identity, and turns out to be n times n plus one divided by two. So if we

wrap this in a big O, we split our equation, we can see that this is big O of n squared. Now let's look at perhaps a more complicated example. Earlier, you may have wondering, how do we ever get these log Eurythmics or linear rhythmic time complexities? So here's a classic algorithm of doing a binary search, which yields actually a logarithmic time complexity. So what this algorithm does is it starts by making two pointers, one at the very start

in one at the very end of the array, then it selects a midpoint between two and checks if the value we're looking for was found at the midpoint, and then has either found it or not, if it has found it, it stops. Otherwise, it discards one half of the array, and adjusts either the high or the low pointer. remark that even in the worst case, we're still discarding half of the array, each iteration. So very, very quickly, we're going to run out of a

range check. So if you do the math, the worst case is you will do exactly log base two of N iterations, meaning that the binary search will runs in logarithmic time. Very cool algorithm, a very powerful algorithm. Here's a slightly different example worth going over. So first, notice that there is an outer loop with a counter I that does and work, then notice that there are two inner loops, one that does three n work another one that does, too, one

work. So the rule we use to determine the complexity of this algorithm is to multiply loops on different levels and add those that aren't the same, generally speaking. So, so using the rule above, we can see that it takes n work to do the outer loop, multiply by three n plus two n for both inner loop Which gives us five n squared, which is big O of n squared. All right, so this next one looks very similar, but it's actually quite different. So on the

outer loop with AI, we have AI going from zero to three n. So there's three n work done on the outside. But we have to multiply that but what's going on on the inside, so the inside j goes from 10, to 50. So that does 40 loops exactly every loop. So that's a constant for the amount of work. Plus however, the second loop, so j is less than and cubed, but j is J equals j plus two, so it's accelerated a little, so we're going to finish that loop

a little faster. So we're gonna get on the inside 14, plus n cubed divided by two, but we have to multiply that by three n. So we wrap that in a big O. So big O of f of n, is going to give us big of enter the force, because And the fourth is the dominant term in our function, f of n. For some other classic examples of Big O. So if we have to find all the subsets of a set, that takes an exponential amount of time, because there are two the

N subsets, finding all permutations of a string takes big O of n factorial. Another classic one is merge sort. So we have n times log in for your merge sort. And if we have to iterate over all the cells of an array of size n by n, we have big O of n m. Time. All right, let's talk about arrays, probably the most used data structure. This is part one of two in the array videos. The reason the array is used so much is because it forms

a fundamental building block for all other data structures. So we end up seeing everywhere. with arrays and pointers alone, I'm pretty sure we can construct just about any data structure. So an outline for today's video. First, we're going to begin by having a discussion about arrays and answer some fundamental questions such as what where and how are arrays used? Next, I will explain the basic structure of an array and the common operations we are

able to perform on them. Lastly, we will go over some complexity complexity analysis and look at some source code on how to construct a dynamic array using only static arrays, discussion and examples. So what is a static array? So static array is a fixed length container containing elements, which are indexable, usually on the range of zero, inclusive to n minus one also inclusive. So a follow up question is what is meant by being indexable?

So answer this is this means that each slot or index in the array can be referenced with a number. Furthermore, I would like to add that static arrays are given as contiguous chunks of memory. Meaning that your chunk of memory doesn't look like a piece of Swiss cheese with a bunch of holes and gaps. It's continuous, all the addresses are adjacent in your static array. Okay, so when and where is a static array used? Well, they're used

everywhere, absolutely everywhere. It's hard to make a program that doesn't use them. In fact, here are a few places you may or may not know that do use arrays. So of course, the first simple example is to temporarily store objects most common use of arrays that you're probably familiar with. Next is that we use arrays as buffers to store information from an input or an output stream. Suppose you have a really large file, for instance,

that you need to process but that file is so big, it doesn't fit in all in memory. So we use a buffer to read small chunks of the file into The buffer or the array, one at a time. And so eventually we're able to read the entire file. I also like to use arrays as lookup tables because of their indexing property. So this is a really easy way to retrieve data from the lookup table if you know where everything is at supposed to be

and at what offset. Next, we also use arrays as a workaround in a programming language that only allows one return value. So the hack we use then is to return a pointer or a reference to an array, which then contains all the return values that we want. This last example is a bit more advanced, but arrays are heavily used the programming technique called dynamic programming, with tabulation to cache already computed subproblems. So a classic example of this might be the knapsack

problem, or the coin change problem. All right, I'm talking about some complexity. So the access time for static array and a dynamic array is constant because of a property that arrays are indexable. Searching, however, it can take up to the linear time because we potentially have to traverse all the elements in the array in the worst case, such as if the element you're looking for does not exist. Inserting appending. And deletion from a static

array doesn't really make sense. The static array is a fixed size container, it cannot grow larger or smaller. When inserting with a dynamic array, this operation can cost up linear time, because you potentially have to shift all the elements to the right, and recopy all the elements into the new static array. This is assuming we're implementing a dynamic array using static arrays. However, appending though, is constant, Doesn't that

seem a little strange? Well, when we append elements to a dynamic array, we have to resize the internal static array containing all those elements. But this happens so rarely, that appending becomes constant time. deletions are linear, for the same reasons that insertions are linear, you have to shift all of the elements over and re potentially recopy everything into your static array. Okay, so we have a static array A I've defined at the top. So

a contains the values 4412 minus 517 6039 100. Currently, all the elements are distinct, but this is not a requirement of an array. Also remark that the very first element 44 has index position zero in the array, not one. This confuses many, many intro computer science students, you have no idea. The confusing part is that most, if not all, mathematics is one base to work computer science is one. Now, if we look at a you can see that it contains

the values 4412 minus 517 6039, and 100. Currently, all the elements are distinct. However, this is not at all a requirement of the array. Also remark that the very first element 44 is indexed, or positioned at index of zero in the array, not one, zero. This confuses a lot of intro computer science students. The confusing part is that most if not all, mathematics is one based while computer science is zero based. This is what causes the confusion.

But Worst of all, is quantum computing. I did research one summer in quantum computing during my undergrad, and the field is a mess. It tries to please mathematicians, computer scientists and physicists all at the same time. And indexing just doesn't work well. Anyways, back to arrays. I should also note that elements can be iterated over using a for each loop something that's offered in some programming languages. It doesn't require

you to explicitly reference the indices of your array. Although the indexing is done internally, behind the scenes, the notation of the square brackets denotes indexing. So array A square bracket zero, close square bracket is equal to 44, meaning a at position zero is equal to the value 44. Similarly, a position one is 12, a, four, six and seven is nine. But a index nine is out of bounds. And our program will throw an exception. Unless you're

in C, it doesn't always throw an exception, unfortunately, okay. Now if we assign positions zero to B minus one that happens if we assign index five B to and if we assign index x to be 25, let's look at operations on dynamic arrays. So dynamic arrays can grow and shrink in size as needed. So the dynamic array can do all similar get set operation static arrays can do but unlike the static array, it grows inside as dynamically as needed. So if we

have a containing 34, and four, there, if we add minus seven, it gets appended to the end. If we add 34, again, then it will add it to the end. And we can also remove elements. So you see here, our dynamic array shrink in size. Pretty cool, right? Okay, so we already talked about this a little bit. But how do we formally implement a dynamic array? Well, the answer is typically this is done with a static array. But this is not the only way,

of course. So first, we create a stack if you're a with some initial capacity, usually nine zero. So as we add elements, we add elements to the underlying static array, keeping track of the number of elements added. Once, we have to add an element with exceeds the capacity of our internal static array, what we can do it again, double the size, copy all the elements into this new static array, and add the new element we need to add, let's see

an example. So suppose we create a dynamic array with an initial capacity of two, then we begin adding elements to it. So the little circle with the slash through it is a placeholder for an empty position. Okay, so we add seven, everything's fine, we are nine, everything's fine. But once we add three, it doesn't fit in our internal static array. So we doubled the size of the array, copy all the elements in, and now we can add three. Now, if we add

12, everything's still okay, we're doing good. And if we add five, okay, we have to do a resize again. So double the size of the container, copy all the LLM elements into this new, larger array, and then finish off by adding five. And similarly, we can add six without any issues. All right, time to look at the dynamic array source code. This is part two of two in the array series. So the source code for this video can be found at the following link

github.com, slash my username slash data dash structures. Also make sure you saw the last video so you know what's going on with this array implementation. Alright, here we are in the array class. So I've designed an array class to support generics of type T. So whatever type of data we want put in this array, that's fine. So here are three instance variables that we care about our, which is our internal static array. Len,

which is the length the user thinks the array is. And capacity is the length of the actual array, because sometimes our array might have more free slots. And we don't want to tell the user that there's extra free slots that are available. That's just our internal knowledge. So there's two constructors. The first one will initialize the array to be of size 16. The other one you give it a capacity, the capacity of course, has to be greater than

or equal to zero. And then we finish Why's our array and cast it to a type T also noticed I put this suppress warnings and unchecked just because of annoying generics in Java. So here are two simple methods size, get the size of the array and check if the array is empty, pretty self explanatory. Similarly forget inset, we just index into the array if we want the value or set it if we want to set the value, technically, I shouldn't

be doing a bounds check for both of these, but I'm not apparently. Okay, clear. So here, we just remove all the data in our array and reset the length. Simple. This next one is the Add method where things actually get a little bit more complicated. So this condition says, Hey, if the length plus one is greater than or equal to the capacity, then it's time to resize my right. The way I'm resizing is I'm doubling the size of the static array. You don't have to double the

size, but I've decided that doubling the size is convenient. So when I double the size, I have to create a new array with the new capacity. copy everything in this is what this line or these lines are doing, it's copying the old values back into this new array, and then it sets the old array to be the new array. And lastly, here, we just copy the new value into our right. So this remove AZ method will remove a particular value at a given index.

First, we check if the index is valid. If it's not through index out of bounds exception, otherwise, grab the data at the Remove index. initialize a new array of size length minus one. Now copy everything into the new array, except for when it's at that remove index. Now I'm sure there's easier ways to do this. But I decided to do the following maintain two indices i and j. increment i and j as you go. But when i is equal to the Remove index, then we skip over the Remove index by fixing j

temporarily and using j to lag behind, if you will while is still in the original array. So I guess pretty clever overall. And then set the array to be the new array we just generated. Reset the capacity and return the data we have just removed. So this next one remove, we scan through the array. If we find the object we're looking for, remove it at the index and return true otherwise return false. Index of is very similar. If you find

it return I otherwise return minus one. Contains just checks if index of is not equal to minus one. All right, this next one, I return an iterator for the array. So an iterator allows us to iterate over the array providing an abstraction for it. So I need to override two methods. And this is has next. So there exists an x element in our array, if the index is less than the length of the array. I should also be checking for concurrent modification

here, just in case someone decides to change the array for some reason why we're modifying it might add that later might not. Also, there's the next method, which just returns the next element in the array relative to the iterator. Okay, and lastly is the to string to get a string representation of this array. Nothing too complicated. Alright, so this is a very simple data structure. It's just a dynamic array. If you look at Java's ArrayList It looks very Very similar to this. Today

we're going to talk about singly and doubly linked lists one of the most useful data structures out there. This is part one of two and the second part we will be looking at some source code on how to implement a doubly linked list. So for today's outline, in the first section, we're going to answer some basic questions concerning singly and doubly linked lists, namely, what are they and where are they used. Next, we'll cover some terminology concerning linked lists, so everyone knows what I mean when I say the head of linked lists versus the tail of the weight class. Then last in the discussion, we'll talk about the pros and cons of using singly and doubly linked lists, then how to insert and remove elements from both singly and doubly linked lists as well as some source code. So stay tuned. Alright, discussion. So what is the link list linked lists is a sequential list of nodes that hold

data which point to other nodes also containing data. So below is an example of a singly linked list containing some arbitrary data. Notice that every node has a pointer to the next node. Also notice that the last node points to no meaning that there are no more nodes at this point. The last node always has a null reference to the next note, for simplicity, I will omit this in the following slides. Okay, so where are linked lists use. One of the places they get used the most is

actually in the abstract data type implementation of lists, stacks and queues because of their great time complexity for adding and removing elements. You also see linked lists and things like circular lists, making the pointer of the last node points the first node. So circular linked lists are used to model repeating events cycles, maybe like having a round robin ordering on a bunch of elements or representing corners with polygon. So definitely allow use as they're

linked lists can also be used to model real world objects such as a line of train carts that could be useful. And moving on some more advanced examples. We also heavily use linked lists and hash table separate chaining, and for adjacency, lists and graph so we'll get to those in a later video. Okay, a bit of terminology surrounding link lists. First thing you need to know when creating a linked list is that we always maintain a reference

to the head of the link lists. This is because we need somewhere to start when traversing our list. We give a name to the last element of the linked list. Also this is called a tail of the list. Then there are also the nodes themselves, which contain pointers. pointers are also sometimes called references. And these pointers always point the next node. You should also know that the nodes themselves are usually represented as structs, or classes

when actually implemented. We'll get to this when we look at the source code. Okay, singly versus doubly linked lists, sort of concerning the kinds of linked lists that there are there are two types, singly linked and doubly length. singly linked lists only contain a pointer to the next node, while doubly linked lists not only contain a pointer, the next node, but also to the previous node, which makes it quite useful sometimes. This is not to

say we cannot have triple or quadruple the length lists, I just wouldn't know where to place additional pointers, pros and cons of doubly linked lists. So there are trade offs. Between picking a singly and a doubly linked list. What are they? If we look at the singly linked lists we observed that uses less memory. Why? Well, pointers to nose can actually take up a lot of memory. If you're running on a 64 bit machine references use eight bytes

on a 32 bit machine four bytes each. So having a singly linked list means you only need one pointer for each node, hence, twice as much memory is saved. a downside however, is that you cannot access previous elements because you don't have access to them. You would need to traverse from the head of a linked lists all the way up to the previous node defined it. Now concerning doubly linked lists with a grid Pro is that having access to the tail we can easily traverse the list backwards, something we can't do with a singly linked list. Also having a reference to know Do you want to remove, you can remove it in constant time and patch the hole you just created. Because you have again access to both the previous and an ex notes, this is something you cannot do with a singly linked list, you would leave the list severed into a downside however, to the doubly linked list is it does

use twice as much memory. Okay, let's go into some implementation details on how we can create linked lists and remove elements from linked lists. Starting with a singly linked list. So here is a singly linked list. I've outlined where the head and the tail is. Now we want to insert 11. At the third position where seven is currently, let's walk through an example. So the first thing we do is we create a new pointer which points to the head.

This is almost always the first step in all linkless operations. Now what we're going to do is seek up to but not including the node we want to remove. So if we seek ahead, and we advanced our traverser pointers, setting it equal to fives next node, which is now 23. And now we're actually ready already where we need to be to insert the next node. So we create the next node, that's the green node 11. And we make 11 elevens. Next pointer, point to seven. And the next steps that change 23

is next pointer to be 11. Remember, we have access to 23 is next pointer, because we have a reference to it with the traverser. Okay, and now we flatten out the list, we can see that we've correctly inserted 11 at the right position. And we're done. Okay, all right time to insert with a doubly linked list. This is much trickier because of all the pointers flying around. But it's the exact same concept. Notice that the dump doubly linked list not

only has pointers to the next node, but also to the previous node, we also have to change those in the insertion phase. Okay, create a traversal pointer, which points to where the head is, and advance it until you are just before the insertion position. So we advanced the traversal by one and now we're just before the node so we start traversing let's create the new node which is node 11. Point elevens, next pointer to equal seven.

Also point leptons previous pointer to be 23. Which we have a handle on because of the traverser. How we make sevens previous pointer equal to 11. So we can go backwards from seven to 11. And the last step, make 20 threes next pointer equal to 11. This is so that we can go forwards from 23 to 11. So in total remarked that we changed exactly four pointers. So we've flattened out the list, you can see that 11 has been inserted in the correct position.

All right now how to remove elements from a singly linked list. So suppose we want to remove the node with a value nine. How do we do this? Well, the trick we're going to use is not to use one pointer but two, you can use one but for visual effects, it's easier to show you how it is done by using two. So we create pointers, travel one and track two for traverser one in Traverse e two respectively. So traverser one points to the head, traverse

or two points to the heads. next node. Now we're going to do is advanced traffic to until we find the node we want to remove while also advancing draft one. Okay, we have found node nine. So this is the stopping point. I'm going to create another pointer to the node we wish to remove so we can deallocate its memory later. Okay, so now I had to have advanced traffic to to the next node Note nine has turned red. I've done this to indicate that

this will that at this point, node nine is ready to be removed. I'm just keeping it around for the visual effect. Okay, so now set trav once next pointer to be equal to trap two. And now is an appropriate time to remove the temporary pointer because doing nothing with it and their temp has been deallocated. Make sure you always clean up your memory to avoid memory leaks. This is especially important in C and c++ and other programming languages

where you manage your memory. Now you can see that nine is gone, and our singly linked list is shorter. Okay, now for the last bit of implementation, let's look at how to remove nodes from a doubly linked list, which is actually easier in my opinion to removing from singly linked lists. The idea is the same, we seek up to the node we wish to remove. But this time, we only need one pointer. I mean one traverse or pointer. Because each

node is singly linked list has a reference to the last node, so we don't need to manually maintain it like we did with the singly linked list. So let's start travel at the very beginning and seek until we hit nine. Okay, we have reached nine. And we want to remove it from the list. To do this set for us pointer to be equal to 15 with access to four and 15 because they are traves, previous and next pointer respectively. Similarly set 15 previous pointer to equal four. Notice that drive is

now read, meaning it is ready to be removed. So we get rid of travel. And now if we flatten out the doubly linked lists, we see that it no longer contains nine. Let's do a bit of complexity analysis on linked lists how good actually are linked lists. On the left column, we have singly linked lists. And on the right doubly linked lists. The complexity for searching in a linked list is linear in the worst case, because if the element we're looking for is

not there, we have to traverse all of the n elements. inserting it the head, though, is constant time, because we always maintain a pointer to the head for a length list, and hence we can add it in constant time. Similarly for the tail. To remove the head of a singly linked lists, and a doubly linked list is also constant time. Again, because we have a reference to it, so we can just move it at and advanced the head by one. However,

removing from the tail is another story. It takes linear time to remove elements from a singly linked list. Can you think of Why? Well, even if we do have a reference to the tail in a singly linked lists, we can remove it but only once. Because we can't reset the value of what the tail is. So we had to seek to the end of the list and find out what the new tail is equal to. W linked list however, do not have this problem, since they have

a pointer to the previous node. So we can continually remove nodes from the tail. And finally, removing somewhere in the middle is also linear time because in the worst case, we would need to seek through n minus one elements, which is linear. Alright time to look at some double e linked list source code. This is part two of two in the linked list series. So the link for the source code can be found on GitHub and github.com slash

Williams he's a slash data dash structures. Please start this repository if you find the source code helpful so that others may also find it. And also make sure you watch the first part of the linkless series before continuing. Here we are in the source code. We're looking at the implementation of a doubly linked list in Java. So first, notice that I have declared a Few instance variables. So we are keeping track of the size of the link list, as well

as what the head and the tail currently are. To begin with the head and the tail are no meaning link list is empty. Furthermore, we will be using this internal node class quite excessively, because it contains the data for our nodes. And it also contains the previous and next pointers for each node since this is a doubly linked list. So we have one constructor for the node, namely the data and the previous and the next pointers themselves, we need

both otherwise, we can't do much. So his first method I have declared here is to clear the list, it does so in linear time by going through all the elements and deallocating them last time deallocates them by setting them equal to No. So we started to reverse or at the head, we loop while the traverser is likely to no meaning there are still elements less and then we do our deallocation business. And at the end, we set the size equal to zero

and reset the head and tail. Perfect. These size and empty methods are pretty self explanatory, get the size and check if the size of our linked list is empty. Okay, so here I have a public method to add an element by default, we're going to append to the end of the linked list or at the tail. But I also support adding to the beginning of the linked list. So how do we do this, if this is the first element, make a list is empty, then we set the head

and the tail to be equal to the new node, which has, you can see here both previous and next pointers set to No. Otherwise, if the list is not empty, then we say the heads previous pointer is equal to this new node. And then we set the head, the head pointer to be whatever hands previous is. So we backup the pointer in a sense. And we also don't forget to increment the size. A very similar thing is done when we want to add to the tail length list, except we're moving the tail pointer around.

OK let's move to peak. So peaking is just looking at either the element at the beginning of the linked list or at the end of the linked list. And we throw a runtime exception if the list is empty, because doesn't make sense to peek an empty list. Okay, now we get to the first more complex method, which is remove first. So this is if we want to remove the head of the linked list. So we can't do much if the list is empty. Otherwise, we'd get the data,

we extract the data at the head, and then move the head pointer forward, we decrease the size by one. So if the list is empty, we set the tail to be known as well. So both the head and the tail are now No. Otherwise, we deallocate the memory of the previous node that we just removed. This is especially important if you're in C or c++, make sure to free or delete pointers, then at the end, we return the data. Very similar thing is done for last

except we're using the tail this time to remove from the tail the linked list and not the head. Okay, and here's a generic method to remove an arbitrary node remark that I set this to private because the node class itself is private so the user shouldn't have access to the node. That's just something we're using internally inside the linked list data structure to manage the list. So if the node that we're removing is either at the head or the tail,

detect that and call our methods either remove first or remove last. Otherwise, we know we're somewhere in the middle of linked list. And if we are we make the pointers adjacent to the to our current node equal to each other. So we're effectively skipping over the current node and And of course, don't forget to clean up your memory and return the data. So we have to temporarily store the data. Of course, before we delete the node, otherwise, we've

deleted the node and the data is already gone. Now, suppose we want to remove a node of a particular index and our linked list. Yes, we can do this. Even though our nodes are not explicitly indexed, we can pretend that they are. So first check that the index is valid, otherwise throw an illegal argument exception. So here, we are trying to be a bit smarter than just naively going through a linked list either when we start searching

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent