From ddbff0dab7a2e63ad84e007874244fae06ac20e8 Mon Sep 17 00:00:00 2001 From: Donne Martin Date: Thu, 14 May 2015 07:30:13 -0400 Subject: [PATCH] Updated Node and LinkedList to allow setting the next pointer on init, or when appending a node. This is useful for circular linked list problems. --- linked-lists/linked-list.ipynb | 13 ++++++------- linked-lists/linked_list.py | 18 +++++------------- 2 files changed, 11 insertions(+), 20 deletions(-) diff --git a/linked-lists/linked-list.ipynb b/linked-lists/linked-list.ipynb index 9be8455..91f74aa 100644 --- a/linked-lists/linked-list.ipynb +++ b/linked-lists/linked-list.ipynb @@ -9,8 +9,7 @@ "* [Clarifying Questions](#Clarifying-Questions)\n", "* [Test Cases](#Test-Cases)\n", "* [Algorithm](#Algorithm)\n", - "* [Code](#Code)\n", - "* [Pythonic-Code](#Pythonic-Code)" + "* [Code](#Code)" ] }, { @@ -155,15 +154,15 @@ "%%writefile linked_list.py\n", "\n", "class Node(object):\n", - " def __init__(self, data):\n", - " self.next = None\n", + " def __init__(self, data, next_node=None):\n", + " self.next = next_node\n", " self.data = data\n", " \n", " def __str__(self):\n", " return self.data\n", "\n", "class LinkedList(object):\n", - " def __init__(self, head):\n", + " def __init__(self, head=None):\n", " self.head = head\n", " \n", " def insert_to_front(self, data):\n", @@ -176,10 +175,10 @@ " node.next = self.head\n", " self.head = node\n", " \n", - " def append(self, data):\n", + " def append(self, data, next_node=None):\n", " if data is None:\n", " return\n", - " node = Node(data)\n", + " node = Node(data, next_node)\n", " if self.head is None:\n", " self.head = node\n", " else:\n", diff --git a/linked-lists/linked_list.py b/linked-lists/linked_list.py index fb42134..cce8a2e 100644 --- a/linked-lists/linked_list.py +++ b/linked-lists/linked_list.py @@ -1,23 +1,15 @@ class Node(object): - def __init__(self, data): - self.next = None + def __init__(self, data, next_node=None): + self.next = next_node self.data = data def __str__(self): return self.data class LinkedList(object): - def __init__(self, head): + 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: @@ -29,10 +21,10 @@ class LinkedList(object): node.next = self.head self.head = node - def append(self, data): + def append(self, data, next_node=None): if data is None: return - node = Node(data) + node = Node(data, next_node) if self.head is None: self.head = node else: