Refactored linked list class. Class is now loaded by other notebooks that reference it.

This commit is contained in:
Donne Martin
2015-05-13 06:39:16 -04:00
parent 6f3e3b0b8f
commit 4c1f87a2ae
3 changed files with 80 additions and 122 deletions

View File

@@ -18,17 +18,13 @@
"source": [
"## Clarifying Questions\n",
"\n",
"* Do we assume the linked list class already exists?\n",
" * No, create one\n",
"* Is k an integer?\n",
" * Yes\n",
"* If k = 0, does this return the last element?\n",
" * Yes\n",
"* What happens if k is greater than or equal to the length of the linked list?\n",
" * Return None\n",
"* Can you insert NULL values in the list?\n",
" * No\n",
"* Can use additional data structures?\n",
"* Can you use additional data structures?\n",
" * No"
]
},
@@ -69,6 +65,17 @@
"## Code"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"%run linked_list.py"
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -77,28 +84,12 @@
},
"outputs": [],
"source": [
"class Node(object):\n",
" def __init__(self, data):\n",
" self.data = data\n",
" self.next = None\n",
" \n",
"class LinkedList(object):\n",
" def __init__(self, head):\n",
" self.head = head\n",
" \n",
" def __len__(self):\n",
" curr = self.head\n",
" counter = 0\n",
" while curr is not None:\n",
" counter += 1\n",
" curr = curr.next\n",
" return counter\n",
" \n",
"class MyLinkedList(LinkedList):\n",
" def kth_to_last_elem(self, k):\n",
" if self.head is None:\n",
" return\n",
" if type(k) != int:\n",
" return\n",
" raise ValueError('')\n",
" if k >= len(self):\n",
" return\n",
" curr = self.head\n",
@@ -112,20 +103,19 @@
" while curr.next is not None:\n",
" curr = curr.next\n",
" prev = prev.next\n",
" return prev.data\n",
" \n",
" def insert_to_front(self, data):\n",
" if data is None:\n",
" return\n",
" node = Node(data)\n",
" if self.head is None:\n",
" self.head = node\n",
" else:\n",
" node.next = self.head\n",
" self.head = node\n",
" \n",
" return prev.data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Empty list\n",
"linked_list = LinkedList(None)\n",
"linked_list = MyLinkedList(None)\n",
"print(linked_list.kth_to_last_elem(0))\n",
"# k is not an integer\n",
"print(linked_list.kth_to_last_elem('a'))\n",
@@ -133,7 +123,7 @@
"print(linked_list.kth_to_last_elem(100))\n",
"# One element, k = 0\n",
"head = Node(2)\n",
"linked_list = LinkedList(head)\n",
"linked_list = MyLinkedList(head)\n",
"print(linked_list.kth_to_last_elem(0))\n",
"# General case with many elements, k < length of linked list\n",
"linked_list.insert_to_front(1)\n",