1. Home
  2. Explore
  3. Computer Science
  4. Linked Lists Introduction

Study methods

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

Linked Lists Introduction

Transcript

A linked list is a common data structure  used in software development. It is also a   frequent topic in technical coding interviews.  In this course, Alvin will explain linked lists   and prepare you to use them both  in interviews and coding projects. Hey, programmers, Alf Infrastruktur, here, welcome  to our course on linkless. What I want to do is   really get you well prepped for those linkless  problems on your technical interviews. So consider   this a little bit of a crash course, like I do in  all of our data structure and algorithm courses,   I want to go through two pieces of information  for every single problem. That is I want to really draw things out visualize things and understand  the theory behind a problem before I go ahead   and implement the code behind it. Right, so we're  gonna do a one two punch for every single problem   here. So this is going to be an introductory  course on linked lists. So I'm going to assume   you know nothing about linked lists, but you're  not a total beginner to programming, right. So you   understand things like a while loops, for loops,  if statements and all that jazz, I'm also going to

assume that you know, a little bit of recursion,  because I'm going to show you some recursive   solutions for many of our linked list problems.  And so without further ado, let's jump right in.   So what I want to do is start by understanding  what a linked list is at a high level bird's   eye view. The first thing we'll need to know is  that a linked list is a type of data structure,   right? So we're organized as data. And in  particular, a linked list is made up of many nodes. So as the first checkpoint here,  we need to first understand what a node is,   you can think of a node as just a container for  some data. So when we conceptually visualize   nodes, you really think of them as some  circles that I can put some data inside   here, I'll put a letter or character inside of  my node. But of course, you can store any data   you like. It could be a strings, numbers, Boolean,  or even other objects, right. And I'm saying that

a linked list contains many nodes. So let's say  had a bunch of nodes, and they can all contain   different pieces of data. So I have the characters  ABCD, stored in different nodes over here.   And if I wanted to make these nodes comprise a  linked list, then what I need to do is add some   links. In other words, if I have a node like a, I  can make it point to the next node, the dataset,   that is a points to B, right, can also say that  B points to C, and C points to D, right. And the term we actually like to use for this is really  saying that A is next is B, right? It's going   to be very common linkless terminology, and a  pattern we're definitely going to see in the code   later on. And now you can already see why you call  this data structure, a linked list, right, have   a bunch of nodes linked together. The important  thing to note here, it's about the last node D,   right? D is the last node in our linked lists.  And so under the hood, we can really represent it

being the last node, by having its next pointer  pointing to nothing or more programmatically,   you can have its next set to null, right, the null  pointer and whatever your language of choices.   So sometimes during this course, I'm  going to explicitly choose to dry out   the null note or the null reference, just  so that we can build some very robust code.   Alright, now that we know what a linkless looks  like, I want to introduce some other terminology that you're going to hear, right. So when we refer  to the very, very first node of linkless, that is   the a node in this diagram, I consider that the  head, it's a very common term. And a similar way,   we can refer to the very last node in a link list  as the tail, right. So if you hear those words,   in problems, we're referring to the first  node and the very last node respectively,   right? If you think about it, because I have this  sense of different nodes, and you know, a first

note and a second node, but you can think of a  linked list as an ordered data structure. In other   words, if I started at the head of the linked  list, I can just look at this nodes next pointer,   and I can go to the B node, so I can just  move to the right. And once I'm at the B node,   I can see that b has an X that goes to the C node,  and the C node goes to the D node, and the D node   goes to the null node, which must mean that I'm  at the end of the linkless. So that's a very, very key characteristic about the linkless. Right?  A nice property to leverage about a linked list is   that it's an inherently ordered data structure,  right? If you want to refer to like the positions   of these nodes, and we do that programmer thing  of starting at zero, I can see that the head has   a position of zero, B has a position of one, and  then we just go sequentially throughout, right.

So there are four nodes within this linked list,  I can see that the position of the head is zero,   and the position of the tail is three. So so far,  we're probably not seeing the full value of the   link list, like when would this data structure  have some real utility over other data structures   that we know about? In other words, you're  probably wondering how a linked list compares to   an array because an array is also an ordered data  structure. So let's do that comparison right now. So here I have my linkless up top, if I wanted  to represent you know, a similar data structure,   but in an array form, it would look something  like this, right? I have an array in memory.   And I know that that array has some indices,  right. So this is a really clear analogy here.   I know that the indices of an array correspond  to the positions of the nodes of a linkless.   Right. And obviously my link was is made of  many nodes. Whereas my array has many elements.

The most important difference between an array  and a linked list is that an array must be stored   contiguously in memory, that means all of your  elements in an array are going to be stored like   right next to each other in your computer's  memory. And that has a lot of consequences   in the runtime of different operations  across your array. Right? So let's say right,   now I wanted to step through a scenario, let's say  I have the goal of inserting a new element Q at index two of my array. And the key specification  here is I want to insert Q at position two,   I don't want to overwrite the current element  at position two, right? So at the start of   this operation, I have four elements in my array  ABCDE. After I do my insertion of Q, I should have   five elements in my array, and they should go A B  QCD, right, because I'm inserting some new element   at index two. So how will this algorithm run at  a higher level in an array? Well, typically, all

you need to do is obviously find the index two,  which is right here. And I know that this is where   I need to put the new Q element, but I can't just  overwrite this value of C, because I want to do an   insertion not overwrite. And so what happens under  the hood in your programming language, when you   perform this insertion operation? Well, we hope  that there's still some empty space in the array, and it should occur after D, right. Assuming that  there's still space in this array, I would need   to shift all of the elements to the right over by  one index. In other words, I need to put d to the   right, I need to put c over a one position to the  right. And now I have perfect room to add this cue   at index two. Right. And of course, now D would be  occupying a new index of four logically. But the

important step we took here was to actually  insert somewhere in the middle of an array,   that could mean that you need to shift over a  bunch of different elements in your array, right.   So in this very small example, I only had to move  over to elements of C and D. But let's say you had   a very long array, and there were, I don't know,  1000 elements after your insertion index, you   would have to shift all of them over one by one.  And that is a relatively costly and slow operation for such a simple move of inserting Q, right.  So we say that when we insert into an array,   that does have an O of n insertion time, right, in  the worst case, if you insert at index zero of an   array, that is you're inserting a very first new  elements, you would have to shift everything over   by one index in the array. And since there are n  elements in the array you're doing and different   shifts. Awesome. Now let's compare that to a  similar insertion operation for our linked lists.

So let's say I still wanted to insert the value  of queue at position two of my link lists. Well,   that means I need to create a new node in  memory. And what's great about a linked list is   it is not required that the nodes are  contiguous in memory. In other words,   we can have these like nodes exist anywhere in  the space of our computer's a memory addressing.   And that's kind of a very low level statement. But  the consequence of this is I don't need to do any shifting when I perform this insertion. In other  words, how does that work? Well, if I want Q,   to be composition to have my link lists, now  that I've created the new Q node, I just need   to adjust B's next pointer. So I'm going to  look at node B, and reset its next pointer   to point at q, then I set Q's next pointer  to point at C. And with those small changes,   I've actually changed, the logical order of  nodes within my linked list would now be this.

Right, queue occupies position to see occupies  position three, and so on. And what's really   great about this is, let's say that there  were many nodes after my insertion position,   let's say there were 1000 nodes, but wouldn't have  to actually modify all 1000 nodes that came after   my insertion point, I just need to change about  two pointers every single time. Because that's   a constant number of operations. I will say that  a linkless insertion, if we write it correctly, will be constant of one time. So here we see  a very tangible difference between our linked   list data structure and our array data structure.  And there are many more a different pros and cons   between these two. But for now, we'll leave it  at that and we can chat more about them as we go   throughout the course I'm sure it's going to come  up. But what I want to do for now is talk about   the core core core, a linked list algorithm  that's just traversing through a linked list.

In other words, how can we just touch and  process every node within a link lists?   Well, the important thing to know is if you wanted  to, like give a link list to someone or in other   words programmatically pass a link list into a  function, you really only need to pass a reference   to the head node of a linked list. Because  if I give you the head node of a link lists,   by accessing the next property of every  node, you can have access to the full sequential list, right? And so to actually  implement a traversal algorithm on a list list,   we just need a handful of variables. Most  importantly, we need like a current variable,   a current reference to look at the current node  of the linked list we're iterating through,   right. So if I have this current node of A, and I  want it to go to the next node, I can just look at   current dot next, right or something similar  in the programming language of your choice,

I can just set current equal to current dot  next, then I would be at the B node. And B also   has an XT. So I do that again, at the C node,  I can just keep continuing this process, right,   assigning current equal to current dot next,  until at some point, once I'm at roughly the tail, current would be D. And so current dot next would  be this null node or this null reference. And if I   set current equal to next, I'll be right at null.  And that can be a perfect condition I can catch.   In other words, we can stop the algorithm when  current is equal to null, we know that that   point would have visited every node of the link  lists. So as I went through this high level trace,

I was kind of speaking upon this algorithm as if  it was an iterative solution. And I'll also show   you how you can solve this one recursively, it's  really the same line of thinking. At this point,   I would want to actually hop into some code. So  we can see the nuts and bolts implementation of   a link list as well as the core traversal  algorithm through a linked list. Alright,   let's do this. So here I am, in my text editor,  I'm going to be doing this in JavaScript, although you shouldn't be able to follow along in  your language of choice. So the first thing I want   to do is just manually build a linked list. And to  start, I'm going to need to create a node class,   right, so we're gonna stay a little bit  object oriented here, just create a node   class. So from JavaScript, I need to give it  a constructor. And in terms of the properties,   we're going to need to store inside of an instance  of Node, I only need two things, I need to store

the actual value. But I also need to store a  reference to the next node in the linked list,   if there even is an x node, right. So to my  constructor, I'm just going to take in the value,   so I can say this dot val equals Val. And I'm just  going to always initialize my next to be null,   right, I can just manually reassign this next  property. And if you have this class or in it,   that's all you need to start creating some  linkless. I'll be it manually. So let's say I want to construct a linkless, I'll just create  a few instances of nodes, I can create node A,   make it a new node, I need to pass in the value to  be constructed, I'll just give it some characters   here, maybe some capital letters this time. So the  character a lot create a bunch of nodes like this,

it's will have my B, my C and my D. I'll give them  some corresponding values. Naturally, I'm storing   strings or characters within the values of my  linkless. But you can make them you know, numbers,   if you want, it's no big deal. What I want to do  now is actually link these nodes together, that   way, I can just have a linked list, I can start  writing a few algorithms on, right. So typically, this part would be kind of taking care for you  already. If you're on an interview, you can assume   that you're taking in a properly structured link  lists. But if I want to just like test some code   for myself, what I can do is say things like A's  next is going to be equal to the B node, right.   So I'm making A's next property, now become the B  reference. So I'm actually linking these two nodes together, right? A's next is pointing to be the  same way, these next is pointing to C, C's next is

pointing to D. And there is no other nodes in my  linked list, I'm going to leave D alone. Because   I know automatically, these next would currently  be pointing to null, which does represent the tail   of my linked lists. So like visually, I think  of this sort of structure, I have a is my head,   that points to B, which points to C, which  points to D. And technically, D points to like,   no, so I'll be explicit here and just draw  that one out. Nice. So now that I have my link list ready to go, let's go ahead and write  our traversal algorithm on it. That is I just want   to iterate through every node of the link lesson,  maybe just print out the value, something very,   very foundational here. And so all maybe choose to  make this its own function, I think that'd be the   best way to go about doing this. So I'll create  a nice function here, I'll call it just print

linked list, it's going to take in the head of  olink list, I'm going to stay kind of abstract   here. And I just like to call it head, right.  There's my nice empty function. And in terms of   how I would actually want to call this function,  the client would have to call print linkless.   And give it like the real head of the link list,  which for me in my little example here is just a   reference to the a node. Cool, so I'm actually  receiving the head node, which is an instance of Node as the head of my link list here. And  so let's go ahead and now set up our algorithm.   So we're gonna really just implement the  algorithm we just traced out on the whiteboard.   So if I want to just traverse through a link  less and print out every node, I'm going to need   to continually update a current pointer. So I'll  say current equal to the head of the link lists,   which means I'm really starting at  the very beginning of my link lists.

And then from there, how far do I need to go  while you want to keep running this algorithm   while your current pointer is not equal to no,  right? Because if current is not equal to null,   then there's some stuff to still iterate through.  And now we get into the meat of the algorithm.   If I wanted to, like print out or process my  current node, I'll just console dot log here,   we're going to print out this current nodes value.  Right. And notice I'm writing all this logic in terms of current, because I hope to update current  properly at the end of every iteration. Right. So   now that I printed out current vowel, what I want  to do is update what current is pointing to. So   what I should do is set current equal to current  dot next. And don't be fooled here. This is a very   simple variable assignment. Right? So let's run  this code. And then I promise that I'll trace   through how this actually operates. It's very  short code, but really the foundation of most

linklist algorithms. So let's give that a run  over here. I hope to print out my characters   ABCD. Awesome. And there I have them. So how does  this code work? Well, let's try to update and   annotate this drawing as we step through the exact  code here, right. So I know that in the context of   my function over here, I'm really only going to  track a really important variable of current. And   that starts at the head of my linkless, which  is passed in as the a node. So technically, give myself some room here, I would say that  the current variable starts by referencing the A note, so I'll kind of represent like  that it's aligned horizontally, right.   Cool. And what I want to do now is consider my  condition. So my condition is checking right?   While this current variable is not equal to  null, then run the code inside of the while loop.   So if I check that on the first iteration of that  condition is true, right, current is not equal to   null. So I can run the code inside, which means  I just print out the value of the current node.

Right? Since current is an instance, of node,  when I do console, log current dot Val, I will   be printing out the A that was initialized inside  of it. So that gives me my first iteration.   Now here's the important part. Right? Now,  I know that current is A, so in this moment,   that means current dot next would be actually  referring to the B node. So if I set the current   equal to current dot next, it has the effect  of literally moving this over to the B note. Now I can check my condition again, is current  not equal to No, that's true. So I print out my   current value of b, and then go to the next. At  this point, the process just continues, right?   The C note is still not equal to null. So  I print it out over here and go to the next   node of D. And this is still true, right? D is  not equal to the null. And so I print out D.   And I actually proceed another iteration,  right. So right now current is D,

current dot next is null. So this would  literally happen, I set my current equal   to no. But things work out great here, because  when I check this condition, I'm going to check   is current not equal to null, in other words, is  no not equal to null. And that's false. So I exit   my while loop. Right. That's how I'm able to print  out every node of my linked list, right ABCDE.   So I think something to draw your attention  to right now is how we write this condition. I think the best way and the most robust way  to write this code is to check while current is   not equal to null. The most common mistake I see  people make is they don't like generally that your   condition should be about like roughly the tail  of your link list. And so they might try to say,   well, current dot next is not equal to no.  Right. But that would actually cut your iteration   short. If I ran that, I would only really print  out ABC, right? Because when I'm at the D node,

right, I would be checking all right, before I  even print out D. What's these next? Well, these   next is no, so I won't even print out D, which is  bad, right? So generally, when you try to write   your algorithms, especially about linkless, try  to write it as like present as possible, right.   So I'm not going to do any premature checking of  the next node, unless I really, really have to,   instead, it's better to actually go to the  next node, and then exit when you actually are at the null pointer, right, the null node.  So let me return this back to its former glory.   And we'll just make sure that this still works  is our classic implementation of a linkless   traversal. It's going to be the baseline code for  almost all of your linklist algorithms. Let's take   this a step further. And I'll show you how you  could write that same logic, but recursively   it's really the same logic, you just turn it into  a recursive call and a base case, right? So let's

go ahead and do this one together as well. When I  promised in the next section, I'll give you a nice   problem to work through. And so if I want to frame  this one recursively What do I need to do? Well,   I like to start with my base. case, your base  case should basically be an analogy for like the   condition you wrote inside of your while loop. In  other words, when are you done with the algorithm? Well, I'm done with the algorithm once. I'm  looking at No, right? So I'm going to say, if head   equals no, then I'm done. So just return.

Notice that here, I'm keeping this argument  named as head, because I think of a link list   as containing many linked lists. In other words,  A is the head of this link lists. But if I look   at the sub list inside B, is the head of its own  linkless, as well, right and see, is the head of   a smaller linkless. Still. So I think that's okay,  terminology to use for a recursive function really shows that you're buying into the recursive nature  here, right? Awesome. So I'm going to stop running   and just return out, once my head is looking at  null. So that'd be once I'm at this point, right.   But in the recursive case, what I want  to do is actually process this node.   So if my head is not equal to null, right now,  then I'm over here, right? What I should do is   just print out this nodes value, right, just like  I did before, I'm just reframing current data set.

And if I want to actually progress to the next  node, like I did, in my iterative solution,   I just do a very proper recursive call here.  So I'm going to call the same function actually   makes it recursive. And what should I specify as  this argument? Well, I just want to give the next   node in the linked list, right, so I'm passing  in head dot next. And that would be all I need   to do for this one, very, very short and to the  point. So let's run this recursive function, then I'll help you trace through it a little  bit more awesome. So it's working, the trace   looks almost the same. But I think it's good if  we do it side by side with the code over here.   And really, the key argument we need to trace  through is the head over here. So on our top level   call, really passing in the a node as head. And so  I checked my base case here is head equal to null,   that's false. So I go into this console dot log,  which means I print out the value a, awesome,

and now I make a recursive call upon the next node  in the linked list. So if head is a, then head dot   next refers to B. And since I'm making a call to  that next node, in this next stack frame, head is   B. And I check the condition again, is b equal to  no, that's false. So I just print out b over here,   and then make another recursive call on B's next,  which is C, right? And this process continues, all the way down to let's say, a when head is D,  right? I check this condition is d equal to no,   that's false. So I go ahead and print out D, which  is like the last logical node in my linked list.   And I would make another recursive call upon DS  next, right? So of head is D, head next is no.   And I would indeed make this call. And now I'm  back inside of this new call, and I check his   head equal to null. And that's definitely true  right now. So I return, that's my base case.

And I end my recursion, right, this base case,  is really, really important. So I want you to   compare and contrast, these two pieces of code,  they really implement the same algorithm. And as   we go through these linkless problems, sometimes  I'll show you both ways to solve it. depending on   you know, what style of problem you're solving,  you might find the recursive or the iterative,   a little easier to write over the other, which is  why I think it's important to practice both, but maybe, you know, choose a favorite and decide what  you're most comfortable with. But that being said,   practice both. Alright, let's head back into the  whiteboard. Hey, programmers, Alvin here, right.   And I want to go over a approach for this link  list values problem. So hop right in right here,   this problem is going to be given the head node  of a linked list we want to do is return an array

containing all of the values within the nodes  of that linked list, we should do it in order.   Bear in mind in this problem, we're given a Singly  Linked List, which means that every node has a   pointer to the next node in the linked list, we  know that the last node of the linked list would   have a next pointer that points to know that being  said, how do we go about solving this one? Well,   there's problems, we're just going to have to  force you to implement a really core linkless pattern that is just traversing through a linked  list in order. And so we'll start by attacking   this one, maybe with an iterative description.  So let's say we started from ground zero,   right? So we want to create our values array, and  to the side, we can just initialize values to be   an empty collection. And to implement this core  pattern of just traversing through a linked list,   we're going to need a variable or just a  pointer. And we're going to start at the head

of the linked list, right? Bear in mind  that our function only takes in the head,   but I know the head is like the ultimate starting  point of the linked list. And eventually I could   access everything throughout the entire list.  So I'm going to set my current equal to the   head. And what I can do off the bat is just check  current value and add it to my running collection.   So I have the a value inside of values now And  since I have access to the current node, I know that if I access its next property, I would have  access to the next node of B. So what I can do is   set current equal to current dot next, basically  just moving my pointer to the next node like this.   Same thing as before I can add my  current value into the collection,   I'll just proceed in this way, right, same  thing for C, set current equal to current next.

And things get interesting once we  approach the tail of this linkless.   So I'm currently at the D node. And I go  ahead and add that value into my values list.   Well, we'll have to do now is consider the  scenario when it's appropriate to actually   stop our traversal. Well, bear in mind that these  next actually points to know. So maybe I'll draw   that explicitly just for this drawing. So these  next is just pointing to null. Which means if I continue this algorithm in the general sense, so  I set current equal to current next, that means   my current pointer now points to know. And I think  that would be a perfect stopping condition. Right?   So once current is no, we know that we've hit the  end of our link list. And so we're totally done.   And if you look at the order of our values,  it is indeed the correct order, right?   What can we say about the complexity of this  algorithm? Well, if we say that n is just the

number of nodes in this link lists, then  the time complexity is going to be O of n,   right? Because we're just are really iterating  through every node once. And our space complexity,   if we consider the output right now would just  be also linear in the number of nodes over here.   And I'll tell you what this looks like a pretty  good strategy, we can go ahead and implement   well implemented in two ways. First, I'll show  you the iterative version, and also show you how to implement this one recursively. Really,  both the iterative and the recursive code   use the same sort of mechanisms. So  I'll see you in the walkthrough video.

Hey, programmers, Alan here, right now want to  go over a JavaScript solution for this linklist   values problem. So we'll jump right in. And we'll  start by implementing, I think, the iterative   version that we spoke about in the approach video.  So if you haven't watched the approach video,   definitely make sure you check that out first,  right. And so I'll get the ball rolling over here,   what I want to do is use a pointer really just a  variable for me, right, so I'll say let current, I'm going to initialize it to be the head. And  I know that though, most important pattern I   probably need for a linked list is just a  traverse in order through a linked list. And   the way that looks is I want to keep iterating  while my current is not equal to null, right,   so just not equal to null, no would mean the  very, very end of my linked list. Nice and very   standard code I need inside is to progress to the  next node of the linked list. So I said current

equal to current dot next. So now think about  actually generating the return type. For this   function, I do want to return an array of all the  values. So I should initialize that up top, I'll   say let's, or maybe const values, because an empty  array. And then as I actually iterate through all   of my nodes of the linked lists, at the tippy top  of this while loop, I can just take my current nodes value, right, every node has a dot Val and  also dot next I'll take the current nodes value,   and just push it into values, right? So values dot  push, that single Val. And once this while loop   is done running, I must have hit the end of the  linked list. So I can just returned the complete   values array. So before we run it, one thing I  want to always emphasize is for your link list,

a main logic, it's always important that you try  to write your logic about just your current node.   So for example, my condition is saying, while  current is not equal to null, it doesn't say like   while current dot next is not equal to no, right,  you can probably get away with finessing code like   that, but ends up being more clunky than anything.  In other words, whenever I try to write my logic for linked lists, I always try to stay very  present, right, so just worry about your current   node. So what I don't like to see is patterns  like this write current dot next dot Val, and try   to just shift your frame of reference because if  you do that, then you're actually kind of assuming   that your linkless has a particular length.  So instead, I always try to write all of my   expressions about simply current, right, so  while current is not equal to null, then I push current dot Val. And then I can just update  current to be current next. And I can be assured   that every node is going to be processed in this  algorithm. So let's give this a test run now.

And if all is well, we can transition into the  recursive version now. Awesome. So how can we   do this recursively I'll just do that down below.  So the way I would structure this one, just so I   get the most optimal complexity is really with two  functions. So my main function will do almost the   same thing. It is going to call a helper function.  I'll call this helper function, maybe fill values. And this function is going to actually do the  recursion. So it's going to take in the head of   the linkless, and also a reference to the values  array. So recall that in JavaScript if I pass   any non primitive types, so basically, things like  arrays and objects, they are going to be passed by   reference, right? So what I want this fill values  function to do is to actually mutate the values   array, because this main function is going to  return it. So what does that recursive function

look like? So we'll say fill values, it's going  to take in the head, and also the values, right?   I'll start with a base case here. And really,  what we're trying to do is just translate the same   patterns from the iterative code just into their  recursive variations, right? And so I know I need   to stop my recursion, once my head is no, right.  So I'm going to check if head is equal to null, then you can stop. So just simply return, right  really important distinction here is, you're going   to have a tough time and probably end up with some  clunky code, if you say, if head dot next is null,   right. So again, I always try to stay very  present, and all of my code, so don't worry about   your next node, just handle yourself, right?  Eventually, every node will get served here.   So if head is null, then nothing much to do just  return and you can stop your recursion. Otherwise,

I know that head is not null, so it must be a  node, I need to take that nodes value and add it   to values, right. So I can say, head dot Val, and  I want to push that into the values collection,   right, we're call that values is referring  to this outer array here. But beyond that,   besides this current head, there could be other  nodes right in the remainder of the linkless. So   I can just call recursively fill values, and  instead of pass along head again, I need to pass along head dot next, right. And that means in  that recursive call and kind of jump back around,   and now head is referring to the next node, and  so on, and then its value is going to be added   all the way until we get to the very, very last  node. Technically, after D, we would hop to   these next, which is no, in which case, we would  exit due to this base case, exactly. And before   we run it, just a few issues that I need to  fix, I see that missing an equal sign here.

And also when I call filled values, of course, you  need to pass along the same values array, because   I know that every call wants to add its value into  the same values array there. So we'll give this a   test run. See what we get. Cool. And now you also  know how to implement this algorithm recursively.   So the reason I like to split up my recursive  version for this algorithm into two functions is so my recursion doesn't actually have to create  like multiple arrays, right? Instead, all of these   recursive calls are just adding their values to  a single array. If I actually created like copies   of arrays all the way through the recursion,  I would end up with like an n squared, sort of   runtime. Cool. So when it comes to comparing these  two implementations, they're actually equivalent

terms of their time and space complexity, right?  All right, programmers. That's all I got for this   JavaScript walkthrough. I want you to practice  both the iterative and recursive versions,   because they're gonna both be very useful for  the next upcoming problems. I'll see you there. Hey, very amorous. Welcome back. Right. Now I  want to go over an approach we can use for this   some list problem. So in this problem, we're  going to be given a singly linked list containing   numbers as the values, what you  want to do is return the total sum   of all the values in the linked list. So for this  particular input, we should return a total sum of   20. And so how can we go about solving this really  just reviewing a core linked list pattern, right,

all you have to do here is just traverse in order  through the link list, and you can accumulate a   sum. So let's say we start from the beginning.  If we initialize some some variable to zero,   we can also just use a pointer that starts at  the head of our linkless. And what we can do is   we can take current value and add it into our sum  just updating the sum. So I take my current value   of to add it to my sum, by total sum is right now  to that I can set current equal to current next, I can add this eight into my sum getting 10. next  iteration, I can add my three into the sum getting   13. next iteration, I can add seven into the some  getting 20. Alright, and I know that technically   seven does have a next pointer, and it does point  to null. So let's say I do that out explicitly.   What I can do at this point is actually continue  my algorithm. And I can make the stopping   condition when my current points to null, right.  So in general, we can call this up by saying a

loop like, you know, while current is not, no,  we talked about the complexity of this algorithm,   it's pretty straightforward. We're definitely  just iterating through every node. So if n is   a number of nodes, we have O of n time,  roughly one iteration of for every node,   and then our space complexity here is actually  o of one if we do this iteratively, right. The   only variables we need to maintain are really just  current and also the sum variable and we're just going to store some primitive values in there. So  we have a nice constant space solution over here.   So the internet It was really straightforward.  Just for, you know, complete understanding how   can we solve this one recursively. If you saw that  recursively, that means you have to, you know,   call your function many times, and we start  with a top level call on the head node of two.

And what this should do is really just call upon  the next node, right? So I could call upon head   dot next session, give me a call to this eight  node, and that should call upon the three node,   and that should call upon the seven node.  And finally, the seven node should actually   call upon its next, which would be the null  node. And that will actually act as my base case,   I think it's a really great one, where I can do  with this base case, right? If my node is null, then I can just return zero, right? Think of no as  if it's an empty linkless. What is the total sum   of an empty list? Well, that would definitely be  zero. So I'm going to plug in this return value,   right? So I'm saying this call to the null node  is going to return zero. When we say return, that   means returned to your caller. So the zero would  actually be returned into the seven node, what

the seven node should do is at its current value,  write its own value into that number, giving seven   and then that returns up the stack. At this  point, I returned back to the three node three   can add its value with that seven getting 10 Just  returning that up, eight can do the same giving   me 18. And finally, two can add itself into that  return value giving us 20. And that would be the correct answer, right. So there are plenty of ways  to implement this one. If we solve it recursively,   we're definitely going to have one call for  every node within our linked list. So that'd   be O of n time. And the space complexity would  actually be a little more than our iterative,   we would have O of n space here because of the  call stack. Right? Typically, when we analyze our   recursive functions, we should include the space  utilize for making these recursive function calls,

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent