push
and pop
method, stacks have other useful methods. Let's add a peek
, isEmpty
, and clear
method to our stack class.
Instructions
Write a push
method that pushes an element to the top of the stack, a pop
method that removes the element on the top of the stack, a peek
method that looks at the first element in the stack, an isEmpty
method that checks if the stack is empty, and a clear
method that removes all elements from the stack.
Normally stacks don't have this, but we've added a print
helper method that console logs the collection.
Stack
class should have a push
method.
testString: 'assert((function(){var test = new Stack(); return (typeof test.push === "function")}()), "Your Stack
class should have a push
method.");'
- text: Your Stack
class should have a pop
method.
testString: 'assert((function(){var test = new Stack(); return (typeof test.pop === "function")}()), "Your Stack
class should have a pop
method.");'
- text: Your Stack
class should have a peek
method.
testString: 'assert((function(){var test = new Stack(); return (typeof test.peek === "function")}()), "Your Stack
class should have a peek
method.");'
- text: Your Stack
class should have a isEmpty
method.
testString: 'assert((function(){var test = new Stack(); return (typeof test.isEmpty === "function")}()), "Your Stack
class should have a isEmpty
method.");'
- text: Your Stack
class should have a clear
method.
testString: 'assert((function(){var test = new Stack(); return (typeof test.clear === "function")}()), "Your Stack
class should have a clear
method.");'
- text: The peek
method should return the top element of the stack
testString: 'assert((function(){var test = new Stack(); test.push("CS50"); return (test.peek() === "CS50")}()), "The peek
method should return the top element of the stack");'
- text: The pop
method should remove and return the top element of the stack
testString: 'assert((function(){var test = new Stack(); test.push("CS50"); return (test.pop() === "CS50");}()), "The pop
method should remove and return the top element of the stack");'
- text: The isEmpty
method should return true if a stack does not contain any elements
testString: 'assert((function(){var test = new Stack(); return test.isEmpty()}()), "The isEmpty
method should return true if a stack does not contain any elements");'
- text: The clear
method should remove all element from the stack
testString: 'assert((function(){var test = new Stack(); test.push("CS50"); test.clear(); return (test.isEmpty())}()), "The clear
method should remove all element from the stack");'
```