Added method to return the length of a linked list.

This commit is contained in:
Donne Martin 2015-05-14 07:34:35 -04:00
parent ddbff0dab7
commit f52450363b
2 changed files with 50 additions and 1 deletions

View File

@ -4,7 +4,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"## Problem: Implement a linked list with insert, append, find, delete, and print methods\n", "## Problem: Implement a linked list with insert, append, find, delete, length, and print methods\n",
"\n", "\n",
"* [Clarifying Questions](#Clarifying-Questions)\n", "* [Clarifying Questions](#Clarifying-Questions)\n",
"* [Test Cases](#Test-Cases)\n", "* [Test Cases](#Test-Cases)\n",
@ -60,6 +60,10 @@
"* Delete in a list with one element or more matching elements\n", "* Delete in a list with one element or more matching elements\n",
"* Delete in a list with no matches\n", "* Delete in a list with no matches\n",
"\n", "\n",
"### Length\n",
"\n",
"* Length of zero or more elements\n",
"\n",
"### Print\n", "### Print\n",
"\n", "\n",
"* Print an empty list\n", "* Print an empty list\n",
@ -126,6 +130,15 @@
"* Time: O(n)\n", "* Time: O(n)\n",
"* Space: In-place\n", "* Space: In-place\n",
"\n", "\n",
"### Length\n",
"\n",
"* For each node\n",
" * Increase length counter\n",
" \n",
"Complexity:\n",
"* Time: O(n)\n",
"* Space: In-place\n",
"\n",
"### Print\n", "### Print\n",
"\n", "\n",
"* For each node\n", "* For each node\n",
@ -165,6 +178,14 @@
" def __init__(self, head=None):\n", " def __init__(self, head=None):\n",
" self.head = head\n", " self.head = head\n",
"\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",
" def insert_to_front(self, data):\n", " def insert_to_front(self, data):\n",
" if data is None:\n", " if data is None:\n",
" return\n", " return\n",
@ -335,6 +356,26 @@
"linked_list.delete('aa')" "linked_list.delete('aa')"
] ]
}, },
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Test length\n",
"# Zero elements\n",
"linked_list = LinkedList(None)\n",
"print(len(linked_list))\n",
"# One or more elements\n",
"head = Node(10)\n",
"linked_list = LinkedList(head)\n",
"linked_list.insert_to_front('a')\n",
"linked_list.insert_to_front('bc')\n",
"print(len(linked_list))"
]
},
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,

View File

@ -11,6 +11,14 @@ class LinkedList(object):
def __init__(self, head=None): def __init__(self, head=None):
self.head = head self.head = head
def __len__(self):
curr = self.head
counter = 0
while curr is not None:
counter += 1
curr = curr.next
return counter
def insert_to_front(self, data): def insert_to_front(self, data):
if data is None: if data is None:
return return