From f52450363b9835a67351edcd6b602490d24aab1f Mon Sep 17 00:00:00 2001 From: Donne Martin Date: Thu, 14 May 2015 07:34:35 -0400 Subject: [PATCH] Added method to return the length of a linked list. --- linked-lists/linked-list.ipynb | 43 +++++++++++++++++++++++++++++++++- linked-lists/linked_list.py | 8 +++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/linked-lists/linked-list.ipynb b/linked-lists/linked-list.ipynb index 91f74aa..d4b6f24 100644 --- a/linked-lists/linked-list.ipynb +++ b/linked-lists/linked-list.ipynb @@ -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", @@ -164,6 +177,14 @@ "class LinkedList(object):\n", " 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", @@ -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, diff --git a/linked-lists/linked_list.py b/linked-lists/linked_list.py index cce8a2e..e27e97b 100644 --- a/linked-lists/linked_list.py +++ b/linked-lists/linked_list.py @@ -10,6 +10,14 @@ class Node(object): 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: