Skip to content

Commit

Permalink
(2.3) Delete node given only access
Browse files Browse the repository at this point in the history
  • Loading branch information
ktorng committed Nov 2, 2017
1 parent 2c81101 commit 6485993
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CrackingTheCodingInterview/ch02-LinkedLists/LinkedList.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ def add(self, value):

self.tail = node

return node

# Remove first node that matches value
def remove(self, value):
curr = self.head
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""
Implement an algorithm to delete a node in the middle of a singly linked list,
given only access to that node
"""


from LinkedList import *


def delete_node(node):
"""
Delete a node given only access to that node
Make that node a copy of next node, and delete next node
O(1) time
O(1) space
:param node: A linked list node
:type node: Node
:return: None
"""

if node.next is None:
node.value = None # Cannot delete if last node
else:
node.value = node.next.value
node.next = node.next.next


a = LinkedList()
a.add(1)
a.add(2)
node = a.add(3)
a.add(4)
node_2 = a.add(5)
delete_node(node)
print(a)
delete_node(node_2)
print(a)

0 comments on commit 6485993

Please sign in to comment.