mirror of
https://github.com/donnemartin/interactive-coding-challenges.git
synced 2024-03-22 13:11:13 +08:00
Added method to return the length of a linked list.
This commit is contained in:
parent
ddbff0dab7
commit
f52450363b
|
@ -4,7 +4,7 @@
|
|||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"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",
|
||||
"* [Clarifying Questions](#Clarifying-Questions)\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 no matches\n",
|
||||
"\n",
|
||||
"### Length\n",
|
||||
"\n",
|
||||
"* Length of zero or more elements\n",
|
||||
"\n",
|
||||
"### Print\n",
|
||||
"\n",
|
||||
"* Print an empty list\n",
|
||||
|
@ -126,6 +130,15 @@
|
|||
"* Time: O(n)\n",
|
||||
"* Space: In-place\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",
|
||||
"\n",
|
||||
"* For each node\n",
|
||||
|
@ -165,6 +178,14 @@
|
|||
" def __init__(self, head=None):\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",
|
||||
" def insert_to_front(self, data):\n",
|
||||
" if data is None:\n",
|
||||
" return\n",
|
||||
|
@ -335,6 +356,26 @@
|
|||
"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",
|
||||
"execution_count": null,
|
||||
|
|
|
@ -11,6 +11,14 @@ class LinkedList(object):
|
|||
def __init__(self, head=None):
|
||||
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):
|
||||
if data is None:
|
||||
return
|
||||
|
|
Loading…
Reference in New Issue
Block a user