Stacks and Queues
Transcript
Alright, this is CS50, and this is week 5 already, wherein we will focus today on data structures, which is a topic we touched on a little bit in in simple form, but today we'll dive all the more deeply and for better or for worse, this is our last week on C. next week, of course, we transition to Python, which is a so-called higher level programming language, which is really, frankly, just going to make our lives a lot easier. We're going to be able to solve a lot of the same problems, but so much more quickly as Humans, but not necessarily as we'll see as fast when we run the code as the computer might have if we were still using a lower level language like C. So indeed thematic over this week and next is going to be the theme that we've seen before of trade-offs. But before we get there, why don't we focus on a couple of data structures that you might encounter in the real world, namely stacks and cues. Let's learn some facts about both of these if we could dim the lights dramatically.
Once upon a time there was a guy named Jack. When it came to making friends, Jack did not have the knack. So Jack went to talk to the most popular guy he knew. He went up to Lou and asked, What do I do? Lou saw that his friend was really distressed. Well, Lou began, Just look how you're dressed. Don't you have any clothes with a different look? Yes, said Jack, I sure do. Come to my house and I'll show them to you. So they went off the jacks, and Jack showed Lou the box where he kept all his shirts and his pants and his socks. Lou said, I see you have all your clothes in a pile. Why don't you wear some others once in a while? Jack said, Well, when I remove clothes and socks, I washed them and put them away in the box. Then comes the next morning and up I hop. I go to the box and get my clothes off the top. Lou quickly realized the problem with Jack. He kept clothes, CDs, and books in a stack.
When he reached for something to read or to wear, he chose the top book or underwear. Then when he was done, he would put it right back. Back it would go on top of the stack. I know the solution, said a triumphant Lou. You need to learn to start using a cue. Lou took Jack. clothes and hung them in a closet, and when he had emptied the box, he just tossed it. Then he said, Now, Jack, at the end of the day, put your clothes on the left when you put them away. Then tomorrow morning when you see the sun shine, get your clothes from the right, from the end of the line. Don't you see, said Lou, it will be so nice. You'll wear everything once before you wear something twice. And with everything in queues in his closet and shelf, Jack started to feel quite sure of himself, all thanks to Lou and his wonderful Q.
All right, our thanks to Professor Shannon Duvall at Elon University who kindly put together that animation, and it's meant to paint a picture of a couple of things that we've all encountered in the real world, but more technically what we just saw were what are known as abstract data types, whereby there are data structures in some sense, but it's really about the design thereof, what characteristics or features or functionality these structures offer irrespective of how they are implemented in terms of lower level implementation details, which is to say you can implement, as we'll see, cues and stacks in any number. Ways which are going to have real world implications for how you can actually use them and what kinds of problems you can solve with them. So let's consider for instance queues in the first place. So a queue is something you sort of experience all the time. Any time you go to a store, uh, go to some event for which you have to line up in a so-called queue,
you'd ideally like there to be some fairness property about that queue, such that if you got in line first, you get into the store first. You get to check out first or some other such goal. Meanwhile, the person who got there last actually is at the end of the line. is at the end of the line and therefore gets served or enters in at the end. So queues have what computer scientists would say is a FIFO property first in, first out. That is, if you're the first person in line, you're the first person to get out of line. And for many problems that is a good solution, certainly if you're concerned with fairness. But more technically, AQ has what we'll call two operations NQ, which is a fancy way of saying getting in line, and DQ, a fancy way of saying getting out of the line from the front of it. But those two operations, if Think about it in code. Could it be implemented with different actual details? And by that I mean this.
Here is one way that we could go about implementing in C code, a queue for a bunch of people or persons who want to line up for something. So for instance, we'll decree that this queue can hold no more than 50 people, like that's the physical capacity, and then we define a structure, which we've done a couple of times in the past whereby this structure has not only an array of persons that we'll call people and that will be. As big as is the capacity, so this is an array of size 50 for 50 such persons. And then we're going to propose that we also keep track in this implementation of a queue of the current size of the queue. So we're going to make a distinction between the capacity, like how many total people can be there and the size, like actually how many people are in line at that moment in time so that you know which of the spots in the array are effectively empty, and we're going to call that whole structure a queue.
Now the catch with this particular implementation and code of a queue. Is what? There is inherent in it a limitation, something you just kind of have to deal with and I see you nodding. What what's your instinct for this? For example, like if you have like. OK, well, I think you hit the nail on the head in that it's only for 50 students or 50 people, which means if a 51st person wants to get into line, you literally have no means of remembering them in this data structure. So how do you solve that? Well, we could just recompile our code after changing the 50 to like 51 or maybe 500 or 5000, but there there's this trade-off because you could still be undershooting the total number of people trying to
get into maybe a big concert in the case of an extreme, but at the same time, If you over allocate memory using 5000 locations in memory, what if only a few people show up? Now you're just wasting memory. And certainly at the end of the day you only have a finite amount of memory in the computer, so you kind of have to decide a priori like before compiling your code, how big is this structure going to be, how much space you're going to waste, and in the end it's all sort of stupid. It would be ideal if instead we could just grow the queue as needed and shrink it, essentially asking the operating system as we started doing last week for more memory. Giving it back if we don't actually need that memory, which is to say can't really do an array in this static sense, and by static I mean we're literally deciding in advance at compilation time how big this thing is going to be. As an aside, this is also a bit annoying for implementing a queue because you have
to somehow keep track of who is at the head of the queue, the front of the queue, because as you start plucking people off, you need to remember who's the next person effectively, but there are ways in code that we could solve this. So let's consider an alternative to a cue which gives us very different properties, namely a stack, and we saw that in the animation whereby Jack used a stack to put his clothes into a box so that every time he got dressed, he sort of took the sweater from the top, from the top, from the top, and might never wear anything other than black as a result. If he does a wash before he actually reaches the blue in the red sweater there. So a stack, as we've just seen, has a LIFO property to it last in, first out. So if I do a load of law. and I plop some more sweaters on this stack. Well, I'm presumably going to use the last sweater that went in first as opposed to trying to create a mess and like you know pull the bottommost sweater out,
which is just going to be a little more effort than it would be otherwise from just taking it from the top. So sometimes last in first out doesn't give you maybe this fairness property you might want for other problems, but it does give you an efficiency, a convenience, certainly. So maybe that might be compelling. And stacks are actually everywhere too. If you've checked your Gmail. Recently, odds are you've opened up gmail.com or Outlook.com, and you've looked at your inbox, and where does the new mail by default end up at the top, at the top, at the top. And I dare say all of us are guilty of sort of neglecting emails that fall below the breaker onto the next page and sort of focusing only on the last in and therefore replying to it first out, which isn't great maybe for the senders of those emails, but it's just how those user interfaces are implemented quite often unless you override those default settings. So how might we implement a stack?
Well, we need to implement more technically two fundamental operations. The analogs of NQ and DQ in the world of stacks are called push, which means push something onto the top of the stack, and pop, which means remove something from the top of the stack also. And the team in the cafeterias and dining halls on campus do this all day long. Any of the cafeterias or dining halls that have stacks of trays, of course, you put the first tray at the bottom and then the next tray and the next tray in the next tray, and which tray do all of you. Pick up well, presumably the one on the very top, because it's even harder to grab the bottommost tray than it would be for something like a sweater. As a result, there's maybe undesirable properties like maybe no one ever gets to the nasty tray at the very bottom of the stack because we're constantly replenishing the top ones. But thanks to gravity like that just happens to be the most appropriate data
structure in the real world for distributing things like trays in a cafeteria. So how might we implement that idea in code? Well, funny enough, we can pretty much use the exact. Same structure we could just rename Q to stack because at the end of the day we need to keep track of some number of people and maybe people's a weird sort of analog here, but we kept everything else the same so why not that? But the size is also something we still need to remember and it turns out it's a little easier to implement a stack in this way because you can always remove it from the end of the array, end of the array, and the first thing that went into the stack, the first in, can always stay at location 0, for instance. But ultimately we could implement it in this way, but we have the same darn limitation. You can still only put 50 sweaters, 50 trays, 50 people into that stack data structure. So this is just one implementation approach.
But that doesn't mean that's necessarily a limitation of stacks and cues. They're abstract in the sense that we could do better. We could maybe start to manage our own memory, move away from statically defining the total size of this array, and just start allocating and de-allocating. That is growing and shrinking. The data structure instead, which is to say we can make these abstract data types much less abstract with actual implementations. Let's consider a data structure that we saw an abstract data type that we saw early on that we didn't necessarily give this name. A dictionary is yet another abstract data type that's sort of everywhere in the world, literally in the world of dictionaries containing words and their definitions, and you can think of a dictionary really in the abstract if you were to draw this on the chalkboard as really just a two column table. Whereby on the left is the word and on the right is the definition.
If it's a physical book, it's essentially the same thing with lots of columns of words on the left, often bold faced, and then the definitions right next to them. You can also see this in the context of like a phone book, which is where we began the course in week zero, where it's essentially a dictionary of names and numbers instead of words and definitions, and a computer scientist would generalize the notion of a dictionary further and just call the thing on the left a key and the thing on the right a value. You and these things are omnipresent in computing and you're going to start to see them all the more today and next week and beyond in that if you just want to associate some piece of data with another piece of data, a so-called key value pair, a dictionary is going to be your go to data type. But even these two we can implement in different ways for reasons that we've already seen,
like maybe there's only a finite size to this dictionary if we're using an array. Maybe we can do better than that, and maybe a The dictionary, if implemented one way, is going to be fast. Maybe if implemented in another way it's going to be slow. So we'll consider these other design possibilities today too in the context of phone books and other data structures as well. After all, if you have an iPhone or an Android phone and Apple or Google only decided that you can have 50 friends because they implemented the Contacts app in an array, I mean that would be an annoying limitation. So presumably they've done things a little more dynamically as we'll do today. So let's focus on the first of the data structures we saw back in week 2, that is an array which we recall was just a chunk of memory where you can store values in it back to back to back, and that was the fundamental definition. The values are back to back to back or contiguous in memory,
and as we've seen, we generally have to decide in advance the size of an array. So for instance, if we want to store 3 values like 12, and 3, it might look pictorally like this or in code, let's go ahead and implement this same idea and take a moment. Whip up our very first program here and we'll call it say Li.c. And in this program, let's just do something demonstrative of how you could use arrays to store 3 things in memory. It's quite simply the numbers 123, but you can imagine it being 3 people's names, 3 sweaters, 3 people, or any other piece of data as well. So I'm going to go ahead and at the top of lists.c include standardio.h. I'm going to then do in main void, so no command line arguments. Then I'm going to go ahead and give myself in a red. A of integers of size 3 called list, and that's how we've done that from week 2 onward. Then just for the sake of discussion, I'm going to hard code some representative values.
So the first value will be at location 0 because the rays are 0 indexed. Then I'm going to do the second value, which will be 2, and then the third value which will be at location 2, but the value will be 3. Now just to prove that we've stored this correctly in memory, let's just do a quick 4 loop 4 in to I equals equals 0. Uh, I is less than 3, I plus plus. And then inside of this for loop, I'm just going to do a quick print F of percent I backslash N printing out the value of list at location I. So it's not a useful program per se, but it gives us an array to play with. It prints out what's in it, so hopefully we will see 12. And 3 on the screen. So let me make this list program
list enter and voila, we're on our way going. All right, but what if now we actually want to uh change that design and be like, oh shoot, I now have a 4th number that I want to store or just bought a 4th sweater or a 4th person wants to get in line or I want to add a 4th brand to my contacts, whatever the scenario might be, it stands to reason that ideally you would plop that 4th value right here in memory. That everything remains contiguous. You're still using an array. Your code doesn't really have to change except for the length. All for all intents and purposes, it's the same implementation using just a bit more memory. But recall that when you declare an array of a fixed size, you only are getting promised that chunk of memory, not necessarily more memory to the right, to the left, above or below conceptually, because recall in the context of your whole computer, you've got this canvas of memory, all of which Represent here bytes and there could be a
whole bunch of actual values or garbage values in memory. So in a more complicated program that 123 sure might end up here, but if I also had created a string in this program, H E L 00 world might have also ended up right next to it in memory, which means I can't just plop the four here because then if I'm still using that string elsewhere in my program, now it's going to say hello world instead of hello world because you're just claiming. The H that bye as your own, which does not in fact belong to your array. Of course it looks like there's plenty of other memory I could use here because these garbage values represented by Oscar are not being used. They've been used in the past, but we treat garbage values as memory we could reuse certainly. So wouldn't it be nice to maybe just plop the 123, and 4 in this chunk of memory over here? And I can totally do that. But of course if I want to do that, I've got to copy the first.
3 values over and then put the 4th 1 there and then presumably give back to the operating system the memory I no longer need. So that in fact when using arrays is a perfectly valid solution and I think we can go ahead and do this in our same program. So let me go back to VS code here and instead of statically allocating memory for this array, and by static I mean literally hard coding, coding the number 3 here in a way that is permanent. Effectively, let me go ahead and do this instead.
At the top of my code, let me delete the static allocation of that that array before, and now let me leverage my understanding, if still preliminary of pointers and memory management from this past week for to just dynamically allocate a guess at how much memory I need initially. So I'm going to go ahead and Use Malloch and allocate space for 3 integers, but integers take up a few bytes, and it usually is 4, but just for good measure, I'm going to say times whatever the size of an in is is the total number of bytes I want. So presumably it's going to be 3 times 4 equals 12, but I'm generalizing it. But then recall that Mao returns the address of that chunk of memory, the address of the first byte. So if I want to create an array effectively called list, I can't just do in list like this yet, but what I could say is that all right, now my list variable is actually going to be the address of an integer
and set Mao's return value equal to that. So in code here, what I've done is I'm asking on the right hand side, the operating system, please give me 12 contiguous bytes in memory. All of those. Of course it can be numerically addressed like OX123, 124, 125. We've had that story before. Mallock by definition, returns the address of the first such byte, and it's on me to remember that I allocated 12 if need be. So I'm just storing the address of that first bye in a pointer called List. But recall from last week there's this functional equivalence we saw between treating a pointer as an array and Sometimes even treating an array like a pointer, the C language sort of lets us do this, this conversion, if you will. So what I could do here now is quite the same syntax as before. I could say Libra 0 gets 1, Libra 1 gets 2, Libra 2 gets 3. And even though I have this fancy new line inspired by week 4, the syntax thereafter can be exactly the same. Why
we'll recall that these three lines here using square bracket notation is just syntactic sugar for the stuff we learned last week. Specifically, I could instead of doing list 0, I could much more arcanely say go to that address in list and put the number 1 there, please. I can say go to the address list plus 1. And put the value 2 there. I could then say finally go to the address at list + 2 and put the number 3 there, but this looks ridiculous and even sort of an experienced programmer might not be inclined to do this if with using fewer keystrokes and more readable code they could just do instead what I did the first time around, which is functionally the same, and just treat that chunk of memory as though it's an array. And the computer will essentially do the requisite pointer arithmetic to figure out where to put 12, and 3. So even though this is still kind of fresh hot off the press from last week, it's exactly the same as we tinkered with last week.
So suppose now that some time passes and I realize for the sake of the story that oh shoot, I need more than 3 integers. I need space for 4 so as to achieve this picture in memory. Well, I could of course just like delete all that code, change the 3 to a 4, redo the whole thing, recompile the code, rerun it, but let me propose that we write our code in a way that allows us to change our mind while the program is running how much memory we actually need. And case in point, if you meet someone new, you want to add them to your phone, well, you. Obviously don't want to have to wait for Apple to recompile the Contacts app, reboot your phone just to add one more person. You want the program just to ask the operating system for more memory for that new person. So in this case, let's just pretend that some time passes and now I want to go ahead and actually change my mind and instead allocate space for 4 integers instead. While I could do something like this, I could just say literally list equals Mao of 4 times size of in.
Semicolon. I don't need to redeclare list on line 13 because it already exists from line 5, but this is bad. Because what have I done wrong here in line 13? I've made a poor decision, yeah, in front. I'm wasting all of the memory I had from line 5 because I'm essentially forgetting where it is. If the list pointer is literally a pointer, like a foam finger pointing somewhere in memory, what I'm really doing is saying point it over here now, but I've completely lost track of those other 3 integers in memory, and that's what we described last week as a memory leak which you could find with Valgrind and if you didn't find it or fix it in code,
eventually the computer and the program would slow down over time. So this is probably bad. It's not good. To just unilaterally change your mind and say no, no, no, forget about that memory. Give me a new chunk of memory, especially if you want to copy the old memory into the new just like I did a bit ago when trying to get the 123 into the bigger chunk of memory that can fit 1234. So how might I do this? Well, a temporary variable is kind of our go to solution. Anytime we need to remember something in addition to something we already have in mind. So let me just give myself a temporary variable called TMP by convention for short. And set the return value of this mala call to that, and then what I could do is something like this, much like my print statement earlier, I could do another 4 loop and say 4 into I equals 0. I is less than 3, I plus plus, and then in this 4 loop I could say treat that new chunk of memory as an array like we can
set the I location equal to the IF location in list. So these lines here. Copy old list into new list. It copies those first three values, and then what I bet I could do at the bottom here is then just manually, I can say go to the 4th location, which when you zero index is technically bracket 3 and set that equal to the number 4. So these lines here. Copy the 1, the 2, and the 3 using a loop and then line 20 here at the moment just adds the fourth value.
And again this is a stupid sort of way to write code in that if you want to put the 4 there, you should have just done it earlier. I'm just pretending that some time has indeed passed in the program and I've changed my mind along the way and I want to let the user add some value to memory. OK, but before we proceed further, I dare say that there are some Other mistakes we should clean up. One of the lessons I preached last week was that any time you use Mallock, what should you do or check for?
You should always what? You should always free. So here I'm clearly not freeing any memory, so I should definitely do that. And there was one other rule of thumb with memory. What should you always do when using male? Yeah. Check to see if null came back, which just means something is wrong, like it's out of memory or something else went wrong, and if you don't do that, your program may very well crash with one of those segmentation faults that we saw, uh, briefly in the past. So it makes the code a lot more bloated, but it is good practice. So let's just check if the list pointer I get back contains null, there's no point continuing on. Let's just go ahead and immediately.
Return one because something has indeed gone wrong and then down here under Maoc again, let's do the same. If the temporary pointer also contains null, now let's go ahead and similarly return one or any other non-zero value. But here's the subtlety and let me combine your two ideas. If I immediately return one on line 20 after the second Mallock call fails, what should I still go back and do first? Yeah, you want to elaborate on your first instinct?
Yeah, I want to still free the first chunk of memory because if we execute line 5 and all is well, which means that line 678, and 9 don't apply like it's not in fact nulled. We got back a legitimate value, that means we have a chunk of memory given to us for 3 integers, which means it still exists down here at line 19 and 20. So if I'm ready now to abort this program and return one to signify error, I first want to free. That original list and say to the operating system, Here's your memory back. Now, as an aside, strictly speaking, this is not necessary because the moment the program itself quits, the computer is just going to give back the memory to the operating system. So when programs quit, the memory leaks sort of go away, but your code is still buggy and generally we're running software that doesn't run for a split second but for minutes, hours, days, continually, in which case it's best practice to squash these memory.
bugs now check for null free any memory so that you never indeed encounter these kinds of leaks. All right, so let's forge ahead a little bit more and let me propose that after we have done the copy, we now want to similarly free the original list. However, what I think we're going to want to do first is, after freeing the original list is remember that the new list is effectively. That which we allocated the second time around. So even though this program's getting a little long, notice that what I've just done is I've said, OK, store in the list variable the address of this new chunk of memory so that list now with a foam finger is effectively pointing here instead of up here. But before that I made sure to free what my finger was pointing at originally the list pointer. All right, lastly, let's just scroll down to the bottom of the code here.
I can manually change the 3 to a 4 just to demonstrate that I've stored all 4 values in here and then at the very end of the program, I think I have to free the list again because now the list is pointing all the foam finger to the bigger chunk of memory, the one. 234 and then I can go ahead and return 0 at the very end because all is hopefully well at this point. Let me go ahead and open my terminal window again and make this version of list. I made a lot of mistakes here, it seems. Let's scroll up to the very first call to undeclared library function mao.
What have I apparently done wrong? Or forgotten What have I done wrong? Yeah, you back. Yeah, so in standard lib.h is where Mao is actually declared. So let's just add that quickly. Let's go ahead and include standard lib.h. In addition to standardio.h. Let me clear my terminal window, rerun, make list. Enter now we're good.list and phew, we see 1234. OK, so at this point in the story, all we've done is write a dopey little program that allocates memory for 3 integers 12, and 3, then changes our mind and allocates more memory. 4 integers,
freeing the original chunk of memory after copying the 1st 3 integers into the new memory and adding that 4th value. But this is kind of a lot of hoops to jump through and let me propose one refinement here. So if back in VS code, we go back into list.c here, it turns out that at least this loop isn't strictly necessary, not to mention the fact that we already have another loop for just printing the list. If I want to more cleverly reallocate memory, it turns out. That there's another function that we didn't talk about last week but is in Stanlib.H2 called Reallock, which, as the name kind of suggests it reallocates memory but a little smarter in that it will try to grow your existing chunk of memory if it can, which is going to be super efficient because then you can just plop the 4 at the very end. Or if there just isn't room there because maybe someone else put Hello world right there in memory elsewhere in your program,
it's going to do all of the copying for you. So what you get back ultimately. A pointer to the new chunk of memory containing all of the original data as well. However, we're still going to have to check for null. We're still going to want to free the original list if something goes wrong and then return one. We're still going to want to add the 4th value because Realo has no idea what more we want to put in the list, but I can in fact delete my other 4 loop whose purpose in life was just to copy all of those integers from old into new. All right, that was a lot. Let me pause for any questions. How does realo know that it should reallocate the memory in least? shouldn't you tell like if you have a lot of mas before?
Very good question. That's because I wrote a bug that we didn't trip over because I didn't compile this version of the code. So the question is how does Reallock know what toreallock? Well, according to the documentation, which I forgot to read, you need to tell Reallock what the address is of the chunk of memory that you do want to relock. So the first argument to re-allock, which I did admit. forget until a moment ago is to put the address of the chunk of memory that you already mallocked earlier so that it knows to go there, see if there's indeed some garbage values it can reclaim at the end of that chunk of memory or if it has to wholesale move things elsewhere in memory to give you 4 times the size of the end this time instead of just 3. But still, things can go. Wrong. Like you still want to check for this null value because reallock might not be able to give you enough memory or your memory could just be so fragmented that even though you want 4 bytes, maybe there's 3 bytes over here, 2 bytes over here, 1 bye over here. If there aren't 4 contiguous bytes, real lock 2 could fail and it will return null to signify as much. Other questions on any of this?
Why do we still need the temp variable for the same reasons as before? Because if we just say list equals real lock and something does go wrong, real lock by definition will return null but not touch the original memory, which case we have now lost track of where that original chunk of memory is, so we can never go back to it to print it, to change it, to free it. So we have to use this temporary variable here. Good question. Other questions, yeah.
So reallock will do two potential things for you. So if the computer's memory looks like this, you're sort of out of luck because Reallock can't give you this bye. However, if it finds 4 bytes down here, for instance, Realo will not only allocate those 4 bytes for you, it will then copy the data for you over to it, which is wonderful because it just means we don't need an extra 4 loop all the time we do this. Yeah, in front.
How does it know how much data to, because how much, how does, how does Real know how much data to copy because the operating system, and you can think of it as the standard library, STDLIB.H keeps track of what memory has been allocated for you in the past. So when you pass in that same address, it knows it has essentially a lookup table, a dictionary if you will, that tells it what memory has been allocated already, so you don't have to worry about that. Yeah, in front.
among the goals here was to demonstrate that there are a bunch of ways in which we can implement these data types, but let's talk more concretely about what we'll call data structures, which are concrete definitions of how you use the computer's memory to lay stuff out in memory, and using data structures, you can implement stacks and cues and dictionaries and all of these other things. So we're going to put into your toolkit today a whole bunch of canonical data structures that like every computer scientist does and should know that you want. Necessarily implement all of the time yourself, but when you use some feature of Python or Java or C++ or some other language, you are choosing among typically implementations of these data structures that someone else has written the code for so that you can just benefit from the functionality and the features thereof like that FIFO property we talked about or
LIFO without having to get into the weeds too much yourself. So when it comes to data structures, let's consider that. We have at our disposal now a few new pieces of syntax and C, and we're going to add just one more today. We saw last week that we have the struct keyword, and we've seen that for a few weeks now. Whenever we want to invent our own data structure, we can use literally struct. We saw in the past that you can use the dot operator to actually go inside of a structure to get at a person's name or their number, and we saw last week the star operator. For dereferencing a pointer, de-referencing an address to actually go somewhere like inside of a structure. Wonderfully today we're going to see that you can actually in some cases combine the dot and the asterisk into a single operator with two characters that literally looks like an arrow, and that will help reflect the yellow and black drawings that we've done over the
past couple of weeks where we have an arrow on the screen pointing somewhere. This literal arrow. Code is going to line up with that same concept. So let's introduce the first of our alternatives to arrays. An array again is a contiguous chunk of memory where the values are back to back to back. Among the upsides so fast because like all of the data is right there. We've seen since week 0 you can do binary search and just jump around randomly by just doing simple arithmetic to go to the middle, the middle of the middle, by just dividing by 2 a couple of times and rounding as needed. The problem with the arrays, to be clear, is that they are statically,
they are statically allocated to be a specific size, maybe 3, maybe 4, but it is a finite value, which is problematic because look at all of the code we had to write just to resize these things again and again. Well, what if we sort of try to preempt that kind of pain and try to just build up a list by linking it together no matter where. the values actually are in memory and move away from this constraint that everything has to be contiguous. After all, as I said a moment ago, if the computer has plenty of memory here, here, here, here, that collectively is more than enough memory, but none of those individual chunks is quite as big as you need for an array, well, heck, let's at least try to leverage all of the available memory and stitch together the data structure as opposed to really holding firm this constraint that the array. Be back to back to back and contiguous. So a linked list is something you can now build using that syntax from last week and
a bit more today in your same canvas of memory so that for the sake of discussion, suppose that we want to store first in our list the number one. Well, we all know already that it might very well exist at an address like OX 123 for the sake of discussion, but it's somewhere there. Suppose that you want to store a second value in memory, but you didn't think about it initially and so you weren't smart enough to put it like right next to the 1 and then the next value next to that. But you know somehow from Mao or similar functions that you could put the number 2 over here at addressOX 456 for the sake of discussion. And similarly, there's room for the number 3 over here at say address OX 789. So already we have a list of values in memory, but because they are not continuous, you can't just do some trivial plus plus trick to go from one to the other because they're differing numbers of bytes apart. They're not just back to back one bye. So what if we try to solve that problem?
In the following way, instead of just using one byte for each of these values, let me waste a little bit of memory or spend a little bit of memory and have some metadata associated with our data. So data is value or values you care about. Metadata is data that helps you maintain the data you care about. So let me propose that we use two chunks of memory for every value, such that the top of each of those chunks represents. Actual Verro you we care about 12, and 3 respectively, and you can perhaps see where this is going. The second chunk of memory that I've allocated to each of these values could perhaps be a pointer to the next one, a pointer to the next one. And if this is the end, we can put our old friend OX 0, aka null, and just treat that as the end of the list implicitly. So even though these things could be any in memory by just storing with each value the address of the next value in memory, creating effectively a treasure map or bread crumbs,
however you want to think of it metaphorically, we can get from one node to the other. And indeed that's going to be a term of art we start using a node, it's just a generic structure that contains data and metadata usually like the number you care about and a pointer to the next such node. Um, these are not to scale as an aside. This is typically 4 bytes. A pointer, as we've discussed, is technically 8 bytes, but it just looks prettier to draw them as simple squares on the screen. So what does this really mean? Well, who really cares about OX1, 23456789? We can really think of this actually as being more of a picture with arrows, but to keep track of this list of three values, I do propose that we're going to need one additional value over here, and it's deliberately just a single square. Because to keep track of this list of three values, I'm going to use just one variable called say list and store in that variable a pointer as we defined it last week,
the address of the first node. Why? Because the first node can then get me to the second. The second node can then get me to the 3rd, and so forth. So what's the upside now? If I want a 4th value somewhere on the screen, I could put it here, here, here, here, wherever there's enough room and just make sure that I update the arrow to point to that next chunk, update the arrow to point to the next chunk. There's no copying of data. 12, and 3 can stay there now forever until the program quits, and we do actually free it, but we can just keep adding, adding, adding, or growing this data structure in memory. So that is what the world knows as a linked list in Python to which you were essentially alluding a list in Python is indeed a linked list. Other languages call these vectors, but they are essentially arrays that can be grown and shrunken automatically, effectively without you having to worry quite as much about it. So how does the code for implementing something? This work. Well,
let me propose that we have this familiar friend of a person which we claimed in past weeks has a name and a number associated with them. We know from last week that strings are not technically a thing in C as a keyword, so that's technically just char, star, name and number, but same idea otherwise, and this is what we defined in the past as a person. So this is a structure we've seen before. I now need to implement the code equivalent of these rectangles, each of which has an integer, and then a pointer to the next such value. So let me propose that we delete what's inside this structure, change the name from person to node, which again is a generic term for a container of values, and let me propose that inside of this new node structure we put literally an in for the number we care about. There's going to be my 123 or 4, and then, and this is a little bit new. Let's include in this structure a pointer to the next such node. It's a pointer in the sense that it's an arrow.

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