From 273d0efcb4aa117b1e334f4c4b010cbbd854b7dd Mon Sep 17 00:00:00 2001 From: Donne Martin Date: Sat, 23 May 2015 17:01:45 -0400 Subject: [PATCH] Added stack method is_empty(). --- stacks-queues/stack.ipynb | 26 ++++++++++++++++++++++---- stacks-queues/stack.py | 5 ++++- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/stacks-queues/stack.ipynb b/stacks-queues/stack.ipynb index 3aa5a35..f9d83ee 100644 --- a/stacks-queues/stack.ipynb +++ b/stacks-queues/stack.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Problem: Implement a stack with push, pop, and peek methods using a linked list.\n", + "## Problem: Implement a stack with push, pop, peek, and is_empty methods using a linked list.\n", "\n", "* [Clarifying Questions](#Clarifying-Questions)\n", "* [Test Cases](#Test-Cases)\n", @@ -42,7 +42,12 @@ "### Peek\n", "\n", "* Peek on empty stack\n", - "* Peek on one or more element stack" + "* Peek on one or more element stack\n", + "\n", + "### Is Empty\n", + "\n", + "* Is empty on empty stack\n", + "* Is empty on one or more element stack" ] }, { @@ -80,6 +85,14 @@ "\n", "Complexity:\n", "* Time: O(1)\n", + "* Space: O(1)\n", + "\n", + "### Is Empty\n", + "* If peek has a value, return False\n", + "* Else return True\n", + "\n", + "Complexity:\n", + "* Time: O(1)\n", "* Space: O(1)" ] }, @@ -124,7 +137,10 @@ " def peek(self):\n", " if self.top is not None:\n", " return self.top.data\n", - " return None" + " return None\n", + "\n", + " def is_empty(self):\n", + " return self.peek() is None" ] }, { @@ -164,8 +180,10 @@ "print(stack.peek())\n", "print(stack.pop())\n", "print(stack.peek())\n", + "print(stack.is_empty())\n", "print(stack.pop())\n", - "print(stack.peek())" + "print(stack.peek())\n", + "print(stack.is_empty())" ] }, { diff --git a/stacks-queues/stack.py b/stacks-queues/stack.py index e8780be..e1a9ddb 100644 --- a/stacks-queues/stack.py +++ b/stacks-queues/stack.py @@ -23,4 +23,7 @@ class Stack(object): def peek(self): if self.top is not None: return self.top.data - return None \ No newline at end of file + return None + + def is_empty(self): + return self.peek() is None \ No newline at end of file