Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Duplication of code #2

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 15 additions & 29 deletions Craking the Coding Interview/2.3_remove_node_linkedlist.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,35 @@
__author__ = 'Minsuk Heo'
__author__ = 'Minsuk Heo & Chris Jones'
"""
Linked List
"""
import unittest

class Node:
def __init__(self, item):
self.val = item
self.next = None

# Class to handle the linked list options
class LinkedList:
def __init__(self, item):
self.head = Node(item)

# Adds a value to the linked list
def add(self, item):
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(item)

def remove(self, item):
if self.head.val == item:
self.head = self.head.next
else:
cur = self.head
while cur.next is not None:
if cur.val == item:
self.removeItem(item)
return
cur = cur.next
print("item does not exist in linked list")

def removeItem(self, item):
# removes a value from teh linked list
def remove_item(self, item):
cur = self.head
while cur.next is not None:
if cur.next.val == item:
nextnode = cur.next.next
cur.next = nextnode
next_node = cur.next.next
cur.next = next_node
break
cur = cur.next

def printlist(self):
def print_list(self):
cur = self.head
res = []
while cur is not None:
Expand All @@ -49,13 +38,10 @@ def printlist(self):
return str(res)


class LinkedListTest(unittest.TestCase):
def test(self):
ll = LinkedList(9)
ll.add(5)
ll.add(8)
ll.add(7)
ll.add(6)
ll.remove(8)
self.assertEqual("[9, 5, 7, 6]", ll.printlist())

ll = LinkedList(9)
ll.add(5)
ll.add(8)
ll.add(7)
ll.add(6)
ll.remove_item(8)
print(ll.print_list())