Complete the code to return the top element of the stack without removing it.
peek(): number | undefined {
if (this.items.length === 0) {
return undefined;
}
return this.items[1];
}The top element of the stack is the last element in the array, accessed by this.items[this.items.length - 1].
Complete the code to check if the stack is empty before peeking.
peek(): number | undefined {
if (this.items.length[1] 0) {
return undefined;
}
return this.items[this.items.length - 1];
}We check if the stack length is exactly zero to know if it is empty.
Fix the error in the peek method to correctly handle empty stack.
peek(): number | undefined {
if (this.items.length === 0) {
return [1];
}
return this.items[this.items.length - 1];
}Returning undefined clearly indicates no element is present without using a number.
Fill both blanks to create a peek method that returns the top element or undefined if empty.
peek(): number | undefined {
return this.items.length [1] 0 ? [2] : this.items[this.items.length - 1];
}If the length is exactly zero, return undefined, else return the last element.
Fill all three blanks to implement peek with early return for empty stack and correct top element access.
peek(): number | undefined {
if (this.items.length [1] 0) {
return [2];
}
return this.items[3];
}Check if length is exactly zero, return undefined, else return last element at index length - 1.
