Check out a free preview of the full Introduction to Data Structures for Interviews course

The "Stack: Peek Method" Lesson is part of the full, Introduction to Data Structures for Interviews course featured in this preview video. Here's what you'd learn in this lesson:

Bianca reviews the peek() method and then discusses other methods to consider such as a method that retrieves the length of the stack.

Preview
Close

Transcript from the "Stack: Peek Method" Lesson

[00:00:00]
>> Bianca Gandolfo: Okay, so like I was saying before, a peek is really similar to pop. For a stack, we wanna peek the last one. For the queue, you always peek the first one. So we wanna return the last newest value without removing it. So it's really similar to this, so I'm just gonna copy this logic.

[00:00:18]
>> Speaker 2: I'm just removing line 27, 28.
>> Bianca Gandolfo: Yep, and just remove the delete.
>> Bianca Gandolfo: And the length change. And really, we could just return that and be happy.
>> Bianca Gandolfo: Yep?
>> Speaker 3: Can I see the constructor up there again?
>> Bianca Gandolfo: Yeah.
>> Bianca Gandolfo: And also, if you wanted to give access to your length, you could do that.

[00:00:57]
>> Bianca Gandolfo: But I would probably do something like get length. Like a method that gets the link or something versus,
>> Bianca Gandolfo: Accessing the length directly. Cuz you don't want anyone to set the length on accident or think that they have to. So it would just be like get length and it would be a function that would just return this to underscore length.

[00:01:24]
There would never be a set length so people can never change the length cuz if someone changes the length then that messes everything else. Which is why I have the underscore there.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now