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.

This commit is contained in:
Donne Martin 2015-05-14 07:30:13 -04:00
parent a4aaa42ce2
commit ddbff0dab7
2 changed files with 11 additions and 20 deletions

View File

@ -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",

View File

@ -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: