1. Home
  2. Explore
  3. Computer Science
  4. C Programming Data Structures

Study methods

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

C Programming Data Structures

Transcript

[MUSIC PLAYING]

DAVID J. MALAN: All right, this is CS50, and this is already week 5. This is our last week on C, and it's also reputed generally to be the most challenging perhaps of weeks, whereby we sort of climax with the material we've been exploring thus far. Sort of metaphorically, it's like we've been going up this hill. And I know it's felt like a lift each and every step, but now things kind of plateau out, I dare say. And even though it's not going to feel like we're suddenly going downhill or things get markedly easy, I do think you'll be able to catch your breath and start to apply a lot of the lessons learned over the past few weeks. So everything that lies ahead. And among the things that lie ahead are exactly these data structures, which you've only touched on briefly so far. We had this look at arrays way back in week 2 already, and we've used those in a few different ways. But arrays are super simple data structure, data structure,

meaning, it's a way to structure your data in the computer's memory, insofar as they have to be generally the same data type, but most importantly, back to back to back. And the catch with arrays, recall, is that you have to decide in advance how big the array is going to be. Do you want size 3? Do you want size 30? 300? But you do indeed have to decide in advance. But there's other things in life-- not only the virtual world, but the real world-- that we might consider a bit more abstractly. And in fact, you're going to start to notice after today, ideally, that the world is filled also with abstract data types, whereby these ways of structuring information, but that don't depend necessarily on the underlying implementation details. That is to say you can implement certain features in life, in code, but there's bunches of different ways to actually implement them at a lower level, whether it's using arrays or, in fact, as we'll see today, other data structures as well.

So while data structures are something very concrete, involving variables and pointers and functions and the like, abstract data types are a little more broadly descriptive. For instance, there are in the world these things called queues. It turns out there's things in the computer world called queues, too. But in the real world, a queue is like, what? Where might you see queues in the real world? Definitely in the UK because they're typically called this there. Like a line in a movie theater, like, lining up for dinner or lunch, or any kind of line. You have queues. Now queues have some kind of ordering, often of people. But certainly, in the virtual world, you might have queues as well. In fact, this isn't as common nomenclature anymore. But if you're printing a bunch of things to a printer, those documents are generally stored in a queue so that they all print out in that precise order. And we can actually see this in the real world.

So we wonderfully have three brave volunteers, if you three wouldn't mind coming on up. First up we have here-- come on over here if you'd like to introduce yourself to the world. AKSHAY: Hi, everyone. My name is Akshay, and I'm a freshman in Canada. DAVID J. MALAN: Welcome. And if, Akshay, you want to line up first right over here in the center of stage. JEFFREY: Hi, everyone. I'm Jeffrey, and I'm a freshman in Thayer, which is better than Canada. DAVID J. MALAN: OK, welcome. If you want to line up second place behind him. JACK: Hi, I'm Jack. I'm a freshman in Matthews, which, as Professor Malan would agree, is the best freshman house. DAVID J. MALAN: OK, Yes. Thank you. Matthews, over there. OK, wonderful. Go ahead and hop in third place behind there. So these guys have formed, what I would argue, is a queue. They've lined up wonderfully in order to receive their sort of thank you prizes. And so, in fact, if I hand these out in the order

in which they kindly volunteered-- we have one thank you here. Thanks very much. We have two thank you's here. Thank you very much. And three thank yous. Maybe round of applause for how easy that was for our volunteers. [APPLAUSE] So it was sort of equitable all around. And notice that the queue actually-- if we geek out about this, actually had some operations associated with it. And I daresay we could somehow implement it in code as well. So a queue or a line in the real world as we know it, is actually an example of a FIFO data type-- First In, First Out. So that's a property of this structure, no matter how you implement it, that describes the equity of how you put the data in and get it out or, in this case, the human volunteers. The first one to line up at the front there, Akshay, got his prize first because he was indeed first in line, and then the second person and the third person. So not all that interesting. You would kind of hope or expect that that's how life

works when people line up or queue. But let's make this now a little more granular in the world of coding. So if you were to implement that same structure in code, be it for a printer, or some kind of Ticketmaster-type scenario where you want to ensure a FIFO property, you would generally have two functions or two fundamental operations-- enqueue, which means to put someone into the queue, and dequeue, which means the opposite to take someone out. And just as FIFO implies, the first in is the first one enqueued, but they're also the first one out to be dequeued. So just some terminology. Now how could we make this in code? Well, if we suppose for the sake of discussion, that you want to have a queue, like a line, that can fit 50 things or 50 people in total, a capacity of 50, we could declare an int and make it a const so it can't actually change and initialize that to 50. And then we could use that elsewhere in our code.

And we could create our own structure, using typedef as well, that includes this many people in an array called exactly that, people-- each one of whom is of type person. So recall from weeks past, we used the struct keyword already. We used the typedef keyword already to invent our own data type called person. So let's just assume for the moment that now exists. But notice that you can actually encapsulate data types inside of data types, even if you've made both yourself. So the world starts to get more interesting when you structure things in this way. But I also have inside of this new struct, which indeed I'm going to call a queue in code, also size. Why is it that I need to keep track of the total capacity of a queue code, but also apparently I constantly have to keep track of the size of the queue? It's a subtle difference, but these two words mean something very distinct. Capacity is and always will be 50 because it's a const.

But size is different, how, just intuitively? Yeah. AUDIENCE: [INAUDIBLE] DAVID J. MALAN: Yeah. So size is going to be the current number of people or things in the queue. And it stands to reason that you've got to keep track of both because otherwise you might have 50 garbage values in memory. If you want to keep track of how many of those values are valid and represent, in this case, persons or people, well, you need to know if there's zero people there or 49 or 50 or anywhere in between. So this is how we might encode-- and we won't go down this road further-- how we might in C code implement the idea of a using familiar syntax by kind of layering some of these ideas we've seen already. All right, but it turns out you don't always want queues, and you specifically don't always want FIFOs. So there also exist in the world, these things called stacks. For instance. If, playfully, I propose that I actually do own different colored clothes-- in fact, I've got a red sweater.

I've got a blue sweater. But if at home, in my drawer or closet, I store all of my sweaters in literally a stack, like this one here, well, it stands to reason that if I'm doing laundry frequently enough, I might wear this on Monday, this on Tuesday, this on Wednesday. Then I might do a load of laundry, and so they're back on top of the stack. And I never actually get to the bottom of the stack here. So this is a very different operation. It's not equitable in the same way our queue was because it would seem that the last sweater I put in is going to be the first sweater I take out. Now this sort of stands to reason that that's obviously how the real world works when you stack clothes together but these things called stacks are everywhere too. Like, in the dining hall, in Annenberg Hall, there's a whole bunch of trays, presumably and unless the dining hall is really busy, there could be one really dirty, nasty tray at the very bottom of the stack that never gets

used because people are constantly taking the ones higher up until they finally refresh them and clean them. In the world of technology, like your inbox, if you use Gmail, I mean, that's actually a stack in and of itself. Why? Because when you get new mails, where do they typically visually end up? Well, sort of at the top, at the top, at the top. And if you're like me, if you get lots of emails that you don't really necessarily get to all of them, you might reply to someone who wrote you most recently and completely blow off someone who wrote you earlier because they've been pushed further and further down, so to speak, in the stack. So these data structures or these, rather data types, are really everywhere. And stacks, therefore, suffice it to say, are not FIFO, First In, First Out. They're the world called LIFO-- Last In, First Out, because the last sweater into the stack is the first one that I actually pull back.

And so we can see this even more clearly with three more volunteers. If you three wouldn't mind coming on up, exhibiting a LIFO property here. If you want to introduce yourselves one at a time. Here we go. MICHELLE: Hi, my name is Michelle, and I'm a freshman in Greenough. DAVID J. MALAN: Welcome, Michelle. If you want to come over here first by the table. SOPHIE: Hi, my name is Sophie, and I'm also a freshman in Greenough. DAVID J. MALAN: All right, Sophie, if you ever want to come over here. ALEX: Hi, I'm Alex. I'm a freshman in Wigglesworth. DAVID J. MALAN: Wigglesworth, nice. Wigglesworth nice. If you want to come in front here. So these three have clearly stacked themselves into exactly this data structure, a stack, which is actually too bad because I only have two prizes this time. So I think I can offer you your prize. And enqueue can offer you your prize. And unfortunately, we can just give you round of applause because you were the first one into the stack. [APPLAUSE] OK.

All right, we actually have a third, but point is hopefully made. So thank you to these three volunteers. That's all we needed you for. But a LIFO then is a data type that indeed has that property, which you might want in some contexts, like your Gmail inbox. You might kind of have to tolerate in the physical world just because of gravity and how closets and drawers work. But it isn't necessarily a property that you want of all data types, for instance. Case in point, in the world of printers would be kind of obnoxious if a lot of people in an office or university or printing to a common shared printer, but only the person who printed most recently is the one that gets their document first. So you'll see in the real world not only queues, but potentially stacks, especially when things maybe get unfair when you're in a store, and the cashier isn't necessarily honoring the first in, first out property.

But as for operations, these two have some vernacular. And so instead of enqueue and dequeue in the world of stacks, we actually generally say push, which means to push something on top of the stack, and pop, which means to remove something from the top of the stack. But top of the stack is the operative word. You're not sliding the blue sweater out from under everything else. You're only operating at the top of the data structure. But it turns out if we think now about stacks as being this abstract idea that have these operations associated with them, in code, we could actually implement them pretty much the same. So notice here, the only difference on this screen here is that I'm calling this structure a stack, but the stack still has some capacity. It still has some size. But if you imagine in your mind's eye how a stack differs in code from a queue, whatever loop you're using, whatever conditionals you're using, you're

probably removing things from a stack, from a different part of the array than you would from a queue. So if you just imagine, maybe you start removing things from the front instead of the back. At the end of the day, you can implement these abstract types using similar code here, but you're going to have to tweak the operations to give the property that you want, FIFO or LIFO. So again, the overarching goal of just introducing stacks and queues at this point is that there is this distinction between an abstract data type, like, some way of organizing information that has certain properties, certain operations. But you don't necessarily need to know or care how it's implemented in code because clearly you can implement it one way or the other and the actual data structures with which you are building those abstractions. So one's high level. One's low level. And indeed, that's the whole purpose of abstraction.

So our friend, Professor Shannon Duvall at Elon University actually brought this same idea to life with a short video in which Jack learns the facts about queues and stacks. So we thought we, for a moment to hammer this home, would dim the lights and hit Play on this short film. [VIDEO PLAYBACK] [MUSIC PLAYING] - 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 to Jack's, 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 wash 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 queue. Lou took Jack's 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 queue. [MUSIC PLAYING] [END PLAYBACK] DAVID J. MALAN: All right, so hopefully now that reinforces really what the stacks and queues are. Let's actually transition now to building things and building on top of where we started in week 2 with arrays and really reach a peak today of sophistication when it comes to using last week's concept that of pointers to stitch together in a computer's memory really any kind of structure that we want. But recall first that arrays indeed had this key property that everything was contiguous back to back to back. So, for instance, if in week 2 onward, we wanted to store three integers in memory, it might look abstractly a little something like this, where we might put 1 and 2 and 3. But the catch with arrays recall is that you have to decide in advance, as per those square brackets,

how big the thing is going to be. And so if you decide in advance with square brackets that you want an array of size three, but later you realize, oh, darn, I want to have a fourth integer or a fifth one, you might have actually metaphorically painted yourself into a corner. Ideally, you would put the number 4, for instance, right here. But again, in the context of the computer's whole memory per last week, there's other stuff going on. So for instance, these might not necessarily all be freely available to use because if you've got 1, 2, 3 multiple variables and lots of functions in your program, well, these other memory locations might be filled with actual values and as well as garbage values. So as per Oscar the Grouch here-- assume that anything with him just represents a garbage value where, sure, we can use that location in memory. But there might actually be valid strings like, hello comma world backslash zero.

And I've kind of grayed out because it's separate from the 1 the 2 and the 3. But there could be another variable in your program that's storing Hello World. And just by chance, because you created that variable after the array, you ended up with an H immediately after the three. So it would seem that you've indeed painted yourself into this corner in that unless you sacrifice that H and wreck that whole string, there's no room for the 4. But is there? I mean, obviously, there's a lot of room for the number 4, not to mention the 1, the 2, and the 3 because all of those garbage values don't mean you have to respect them. You can reuse those locations. They're garbage in the sense that you use them already, but you're no longer using them. So I could put this 1, 2, 3, and 4 somewhere up here, somewhere here, maybe even somewhere down here. So how could I then accept the fact that I do want to grow this array?

Well, I could just say, fine, I'm going to have to bite my lip and just copy the 1, the 2, the 3 to a brand new location that actually has room for a fourth value as well. And we can put the 1, the 2, the 3, and we can now have room for the 4, and then we can get rid of the original array somehow. So this is a solvable problem, even though we haven't had to do it in code yet. But what's a downside of this solution to growing an array to store more data after you first create it?

AUDIENCE: It takes up more space. DAVID J. MALAN: It takes up more. Well, it takes up more space in a good way at the moment, I think it's not so much space that we're worried about here. I'm sorry? Yeah, you have to keep doing this again and again. So if I can put words in your mouth, it takes more time because now just to insert one value like the number 4, instead of just jumping to a free location and putting it there in constant time, I kind of have to incur linear time to copy the original array into a slightly bigger array and then add that new fourth value. So you're just kind of wasting your own time. Now, there's a potential alternative. What could we do? Well, I could have just allocated more space than I need from the get-go. So even though I asked the compiler for three integers, maybe it could be a little generous. And just give me four secretly or five or 500 or heck 5,000 so that I never deal with this problem in the future.

That way, everything would be super fast because I never have to waste time moving things. But what would be the downside of that approach sort of over allocating memory for an array? sorry? SPEAKER Waste of space. So it's a waste of space. I mean, there's only a finite amount of memory in your Mac, your PC, your phone. Why are you going to write code that's sort of designed intentionally that way, but arguably poorly designed because you're just throwing memory away that no one can actually use? None of your other programs or apps can actually use because you just want to make sure you can grow this array in case you ever need it.

So that, too, doesn't really feel like a compelling trade-off. But here is really a theme now that we'll see really throughout the semester and throughout computing. There's always going to be some trade, and it's very often between time and space. But as we've discussed in the past, it might be a trade-off between the complexity of your code. I mean, honestly, imagine in your mind the sort of for loop or the while loop that now you have to write code for to copy all of that from old to new array. That's added complexity. We're wasting my human time. We're introducing more lines of code that increases theoretically the probability that one of them has a bug. So there's just lots of trade-offs of solving problems in this or really any other way. So what might we do? Well, what if we could structure our data little more intelligently? Rather than just use this super simple data

structure called an array, where everything has to be back and back and back, could we instead treat the computer's memory kind of like a Canvas, such that if there's free space over here, fine, I'm going to put something over here? If there's free space over here, fine. I'm going to put it over here. Can I just then stitch these things together somehow? And I'm using that word deliberately because last week, we saw pointers which are just addresses. But maybe I can metaphorically-- and as per the arrows I drew on the screen last week, maybe I can just connect the locations in memory that are available so that I no longer need to care if my data is back to back to back in memory. I can just sort of follow arrows from one piece of data to another. And all we need for this is some mostly familiar syntax. One, we have struct, which is the keyword with which we can create a structure, our own data type, along with typedef.

There's dot, which we haven't used that much, but we did see a while back whereby using the dot operator, you can go inside of a structure to get at the name or the number field, for instance, in a person. And then, of course, we spent last week really focused on the star operator. So the asterisk whereby you can use pointers in some way. So using just these three, we can actually build most anything we want structurally in our computer's memory. And in fact, the only new piece of syntax today is going to be this, an arrow, which is just a hyphen and a greater than sign, which, as we'll see, is the exact same thing of using a period and a star together. We'll see what that means in just a bit. So how can we go about implementing an alternative to arrays that actually allows us to grow and even shrink them if we want without having to move everything that already exists in memory around in some way? Well, let's see where we might begin with arrays alone.

Let me go ahead and create a file called list.c and in list.c, let's includes standard io.h at the top. Let's declare int main with no command line arguments. And then let's super simply do int list 3 to give myself an array, called list of size 3. And then just for the sake of discussion, let's go ahead and put at the zeroth location. That is the first, the number 1. At the location 1, the number 2. And at location 2, the number 3. So even though the array recall is zero indexed,

I'm going to use some human numbers like 1, 2, 3 in sequence like this. And then let's just do something mildly interesting, like for int i equals 0 i less than 3 i++. And then inside of my loop, let's just print out those numbers just to make sure that they are printing as I would expect. All right, so if I scroll up to the top of this code, there's not all that much going on, other than I'm creating an array of size 3 with the numbers 1, 2, 3. And then I'm printing them out with a simple loop. All right, let's do make list. So far, so good, dot slash list. And there we go, 1, 2, and 3. All right, so that works perfectly fine so far, but let's actually see what would be involved if we are using arrays alone to grow and shrink this array. So let me go back into my same program. Let me throw pretty much all of this array for-- all of this away for the moment. And let me propose that we're going to create the array in a different way, in a way that we haven't done before.

I'm going to say int star list equals the return value of malloc, whereby I want 3 times the size of an int. So I've not actually created in class at least an array in this way. But if an array is just a sequence of values contiguous in memory, and malloc we saw last week is just a function that gives you a chunk of contiguous memory, I could kind of do things the old fashioned way and use malloc to give myself a chunk of memory and then treat the first part of it as space

for an int, the second part as space for another int to the third part as space for a third int. I'm just kind of doing things at a lower conceptual level. Of course, to use malloc, we needed to include last week standard lib dot h. So that gives me access to that. And recall that sometimes things can go wrong. What does malloc return if there's no memory available anymore? Null. So NU-L-L, two L's in the context of memory. So if this list value happens to equal equal null,

well, there's nothing interesting to do here. Let's just return one and exit the program altogether. But if we don't have that error, let's assume that I did get back a chunk of memory that's big enough for three integers based on whatever their size is on the computer I'm using. So let's now initialize this array. List bracket 0 gets 1. List bracket 1 gets 2, and list bracket 2 gets 3. So just as before, I'm initializing it in the same way. But now, let's suppose that time passes.

And I decide that, oh, darn it, I really wish I had allocated space for a fourth integer. Now, obviously I can just change this code quickly, but let's assume that this is a much more complicated program. It's running all the time. And maybe it's up to the user to say when they are ready to give me a fourth integer. So this is a simplification. But at this point in my story, after some time has passed, let me propose that, darn it, I've painted myself into that corner. Let's reallocate a new array that's a little bigger. Well, how can I do that? Well, let me go ahead and temporarily give myself a variable called temp, TMP for short, set that equal to the return value of malloc, whereby I'm asking now for four times the size of an int. So I'm just sort of changing my mind. Later on in this program, I actually want an array of size 4. OK. I still have to check that nothing went wrong. So if temp equals equals null, then let's go ahead and return 1.

Then let me go ahead and copy everything from the old array into the new array. So how do I do that? Well, I can do for int i equals 0 i less than 3 i++ just like I was printing the thing out earlier. And I can say, put into the temporary array at location i whatever is in the original array at location i as well. So this is kind of like the string copying program we wrote last week where I did everything manually by copying one into the other. Now I'm just doing it more generically for integers into arrays. Then if I want to go ahead and add a fourth number to this array, I can literally do temp bracket 3 gets 4-- and I'm saying gets to mean assignment here. And that's just adding now the fourth value to the array, just like I did a moment ago by plopping the 4 into the bigger chunk of memory. All right, I'm almost done here, but I do need to do some cleanup. After I have created this new array of size 4.

I don't think I need the original array of size 3. So recall from last week, I can free the original list, and that just hands it back to the operating system. And then if I want to keep this new chunk of memory around, you know what? I'd rather call it list instead of temp. So because both of those are just variables, I can simply say, list equals temp. And this just sort of renames that new bigger chunk of memory to be the actual list that I care about. So that moving forward in this program, I can continue to use that array instead of the original. And heck, if I want to now print this thing out, I can do for int i equals 0, i is less than 4 i++. And then inside of this loop, I can print out using printf and percent i backslash n, whatever is at list bracket i, which can now go up to index 4, not through but up to index 4 because there's four possibilities there. And then at the very end of this program, I should probably be a good citizen.

So maybe time passes again. But eventually I should free that list itself. I already freed the temporary the original list. Now, I want to free the new bigger list as well. And now I can just return successfully 0. All right, if I didn't mess this up, let me open my terminal. Do make list again, dot slash list And I should see 1, 2, 3, 4. And I think this is now correct. But notice that just to make this simple idea-- I mean 44 lines of code just to make an array slightly bigger, if you will.

And there's actually a subtle bug. This is super subtle, but it's the kind of thing you need to start thinking about whenever you're manipulating memory. And I'll call this one out myself. So notice that at the very beginning of this program, when I initialized space for three integers, I realized something could go wrong because list could be null. And OK, I'm going to exit immediately by returning one. But there's another subtlety here, which I didn't fix yet. And Valgrind eventually might catch this for me. Notice here I again use malloc, and I did realize here, oh, shoot, something could go wrong. And malloc could again here return null, so I do check for that. But notice that I return before cleaning up the memory that I already asked for. So this is super subtle. But what I should really do at this second use of malloc is if I didn't have a valid return value for malloc, that's fine,

but I had better free the successful value of malloc that I got earlier. Otherwise, this is the definition of a memory leak. If you've allocated memory here, you're exiting your program here, but you never actually give this memory back-- like, that's a memory leak. And to be fair, the operating system will eventually reclaim that memory for you. But if we use this as sort of a working principle, you should always, always, always free memory that you yourself have allocated, whether it's in cases of error like this or intentionally, like, down here. All right, let me go ahead and just make sure I didn't break anything. Make list dot slash list. And voila, we have now 1, 2, 3, and 4. All right, let me propose that this is not actually as annoying as it needs to be when you want to grow a list of size 3 into a list that's slightly bigger of size 4. There's actually one other function we can introduce today

that will make our lives a little easier. Let me go back to VS Code, hide my terminal window. And let me propose that what we could do is actually this. After some time has passed inside of main, instead of allocating a brand new array like this of size 4, we can actually do this instead. We can use a function that we've not seen before called realloc and just ask really C to do the reallocation for me. And this is nice because what C is going to do is if we get lucky, and it is not the case that we painted ourself into a corner, so to speak, and there's no Hello World right after the 1, 2, 3, realloc is going to be smart. And if it can leave the 1, the 2 and the 3 in their current locations, but just give you a little more memory to the right of that array, so to speak, realloc is going to do exactly that and give you back the same chunk of but a slightly bigger version of that memory. So you therefore, do not need to move everything around

in the computer's memory yourself. Now, in order for realloc to do all of that, we actually do need to tell it what the address is of that original chunk of memory. So unlike malloc, which takes only one argument, realloc actually takes two-- the first of which should indeed be the address of the chunk of memory that we are trying to resize. Now, Just like malloc, realloc might also return null in the event that maybe not enough memory is available. So we still need to check for that return value, immediately freeing the original list and returning one as needed. But what we don't need anymore is this chunk of code here, wherein we were previously copying from the old chunk of memory to the new chunk of memory all of those values because that, too, is among the features that realloc provides for us. But my god, I mean, still, what? Now we're down to 40 lines of code instead of 44. It's not a huge gain.

So is there perhaps a better way to go about this process of actually resizing arrays if and when we need more memory? And yes, now that we have access to pointers from last week functions like malloc-- now realloc as well as-- free-- we can actually build a memory structure, a data structure that doesn't need everything being moved around, ever. We can leave everything where we put it in the first place by way of a structure called now a linked list. So what then is a linked list? Well, let me propose that a linked list is a list whereby you're just using pointers to link things together in the computer's memory. So, for instance, if here is our Canvas of memory, and there's a lot of places that things could end up in this story, suppose that I want to store the number 1 first. Well, that location happens to be available. And so I plop the number 1 there. We know from last week that every byte in a computer can be uniquely addressed.

Just like this building is 45 Quincy Street, this is maybe byte number OX 1, 2, 3 Using last week's hexadecimal notation. Now, suppose for the sake of discussion, that maybe this space is being used. This space is being used. This space is being used. So there's no room at the moment. Immediately next to this number 1. That's OK. Why don't I go ahead and plop the number 2 where there is room, which is maybe over here? Maybe that location for the sake of discussion is OX 4, 5, 6. Where do I put the 3? Well, maybe it ends up over here, and that happens to be location OX 7, 8, 9. So no longer are these three integers contiguous. Back to back to back, they're sort of all over the place in memory, but that's OK because if I can somehow connect these dots by pointing one to the other, one to the other, maybe I can kind of stitch together a data structure in the computer's memory. And I can if we used last week's building block of pointers.

Let me waste a little bit of space by using another byte. Or technically, it might be as many as eight more bytes. So this is not drawn to scale. But pointers, recall, typically take up eight bytes or 64 bits nowadays. But I want to draw these things more cleanly as simple rectangles here. So here's still an int. Here's still an int. Here's still an int. But let me propose that if for every integer in this list, let me also allocate a pointer, a pointer, and a pointer. So each one can point to another location. So what should this pointer point to? Well, ideally it should point to OX 4, 5, 6. What should this one point to? Ideally OX 7, 8, 9. What should this point to? Well, if this is the end of the list, we need some kind of special sentinel value. And in the world of memory, what's the only sentinel value we've seen thus far that can kind of signify the buck stops here, there's no more list? So null. So OX 0, really.

So just arbitrarily but universally, we decide to use 0 as a special address. That just means there are no more numbers in this list, a.k.a. null, as we saw last week. Now, this is all fine and good. Memory address, memory address, memory address, and we're stitching things together in this way. But you don't need to think at this low level. Recall from last week, you can think of pointers as-- for the sake of discussion like last week, you can think of pointers as really just pointing from one location to another. And so we can abstract this away and just get rid of all of that and use some basic arrows instead. So how do we keep track of a linked list? Well, a linked list of numbers-- well, we store the numbers themselves wherever there's space in memory. We use some extra pointers associated with each of those numbers to link us from one to the other. And then the linked list itself, it turns out,

we're going to spend one final pointer that just keeps track of where the start of or the so-called head of the list begins in memory. So what's the upside here? Well, the problem I claim we have solved is we no longer need to have things contiguous back to back in memory, which means we can make much more efficient use of memory because we don't need a huge chunk of memory to be available all contiguously. Especially if the program's running over time, you can just start plopping things wherever you have room. Now, for those familiar, that actually can lead to something called fragmentation of memory, where your data structure is kind of fragmented all over the place. But nowadays on modern systems, not really a big deal. And these pointers allow us to get from one location to another. But clearly, even in this picture alone, there is a downside. There is a cost for linking numbers together in this way with pointers.

What is the downside of linking them together here? Twice as many? It looks like it's twice as much space, and it frankly might be a little bigger than that. If these pointers are particularly large, you're spending space, but you're gaining the flexibility of no longer needing to copy everything from one smaller location to one bigger location. And if you've got lots going on in memory, you can actually use all available memory, as opposed to telling the user, sorry, I've got a lot of bytes available, but some are here, some are here, some are here. I just don't have them all contiguous for you. That would be really obnoxious if the program can't proceed because you have enough memory, but it's not all in one place. And you don't want to spend linear time shuffling everything around. A linked list just gives you flexibility. You can use what memory is available, albeit at the cost of these pointers. So it's not a win-win, but it is a trade-off,

depending on what feature is most important to you. All right, any questions on this here structure called the linked list thus far? Any questions at all? No? All right, so let's translate this to the simplest code that we can, and it's actually not all that different from some of the syntax we've seen. Here is how I might remember, implementing a couple of weeks back now, a person whereby originally it was a string name and a string number. We took away those training wheels.

And we revealed last week that it's char star name and char star number, but this is indeed as a person. But this allowed us, using struct and typedef together, to create a new structure in memory that encapsulated information we cared about, like, a person's name and number. Well, let me propose today that we actually introduce a new term of art, node. It doesn't really have a technical definition as much as it is just a container for data in memory. So node is very common in graphs and other types of structures, but node is like a generic rectangle that stores some stuff for us. What could I put inside of this data structure in C to implement that concept of a rectangle with both a number and a pointer to another number? Well, I can literally say int number. So inside of every rectangle, a.k.a. node is going to be an integer called number. And then this one's a little weird.

I'm also going to store a pointer called next that points to another node. So we've not seen this word node before, but it's the same idea as char star. But instead of pointing to the address of a character, this variable next is going to point to the address of another node. And this is somewhat subtle and a little annoying. But because C reads code top to bottom, left to right, there's a bit of a gotcha here. I am not allowed to use the word node here if it only technically exists once I get to the final line of this code. So a little subtlety in C. There is a fix, though. I Didn't need this for person because persons did not involve linking things together in this way. But if I add the word node here-- so it's a little more verbose, typedef struct node, then I can change this to struct node star as well. So now I've seen them top to bottom. This can stay the same. That's the solution to that problem. And this is how everyone does it in C.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent