Polish queue challenge and solution (#70)

Update constraints, algorithm discussion, and code.
This commit is contained in:
Donne Martin
2016-06-19 20:08:26 -04:00
committed by GitHub
parent 4cdb85e22d
commit 0d20ff5931
3 changed files with 46 additions and 40 deletions

View File

@@ -34,11 +34,13 @@
"source": [
"## Constraints\n",
"\n",
"* If there is one item in the list, do you expect the first and last pointers to both point to it?\n",
"* If there is one item in the list, do you expect the head and tail pointers to both point to it?\n",
" * Yes\n",
"* If there are no items on the list, do you expect the first and last pointers to be None?\n",
"* If there are no items on the list, do you expect the head and tail pointers to be None?\n",
" * Yes\n",
"* If you dequeue on an empty queue, does that return None?\n",
" * Yes\n",
"* Can we assume this fits memory?\n",
" * Yes"
]
},
@@ -68,8 +70,8 @@
"\n",
"### Enqueue\n",
"\n",
"* If the list is empty, set first and last to node\n",
"* Else, set last to node\n",
"* If the list is empty, set head and tail to node\n",
"* Else, set tail to node\n",
"\n",
"Complexity:\n",
"* Time: O(1)\n",
@@ -79,12 +81,12 @@
"\n",
"* If the list is empty, return None\n",
"* If the list has one node\n",
" * Save the first node's value\n",
" * Set first and last to None\n",
" * Save the head node's value\n",
" * Set head and tail to None\n",
" * Return the saved value\n",
"* Else\n",
" * Save the first node's value\n",
" * Set first to its next node\n",
" * Save the head node's value\n",
" * Set head to its next node\n",
" * Return the saved value\n",
"\n",
"Complexity:\n",
@@ -126,29 +128,30 @@
"class Queue(object):\n",
"\n",
" def __init__(self):\n",
" self.first = None\n",
" self.last = None\n",
" self.head = None\n",
" self.tail = None\n",
"\n",
" def enqueue(self, data):\n",
" node = Node(data)\n",
" if self.first is None and self.last is None:\n",
" self.first = node\n",
" self.last = node\n",
" # Empty list\n",
" if self.head is None and self.tail is None:\n",
" self.head = node\n",
" self.tail = node\n",
" else:\n",
" self.last.next = node\n",
" self.last = node\n",
" self.tail.next = node\n",
" self.tail = node\n",
"\n",
" def dequeue(self):\n",
" # Empty list\n",
" if self.first is None and self.last is None:\n",
" if self.head is None and self.tail is None:\n",
" return None\n",
" data = self.first.data\n",
" data = self.head.data\n",
" # Remove only element from a one element list\n",
" if self.first == self.last:\n",
" self.first = None\n",
" self.last = None\n",
" if self.head == self.tail:\n",
" self.head = None\n",
" self.tail = None\n",
" else:\n",
" self.first = self.first.next\n",
" self.head = self.head.next\n",
" return data"
]
},
@@ -300,7 +303,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.4.3"
"version": "3.5.0"
}
},
"nbformat": 4,