This notebook was prepared by Donne Martin. Source and license info is on GitHub.

# Solution Notebook¶

## Constraints¶

• Can we assume this is a non-circular, singly linked list?
• Yes
• What if the final node is being deleted, do we make it a dummy with value None?
• Yes
• Can we assume we already have a linked list class that can be used for this problem?
• Yes

## Test Cases¶

• Delete on empty list -> None
• Delete None -> None
• Delete on one node -> [None]
• Delete on multiple nodes

## Algorithm¶

We'll need two pointers, one to the current node and one to the next node. We will copy the next node's data to the current node's data (effectively deleting the current node) and update the current node's next pointer.

• set curr.data to next.data
• set curr.next to next.next

Complexity:

• Time: O(1)
• Space: O(1)

## Code¶

In [1]:
%run ../linked_list/linked_list.py

In [2]:
class MyLinkedList(LinkedList):

def delete_node(self, node):
if node is None:
return
if node.next is None:
node.data = None
else:
node.data = node.next.data
node.next = node.next.next


## Unit Test¶

In [3]:
%%writefile test_delete_mid.py
import unittest

class TestDeleteNode(unittest.TestCase):

def test_delete_node(self):
print('Test: Empty list, null node to delete')

print('Test: One node')

print('Test: Multiple nodes')

print('Test: Multiple nodes, delete last element')

print('Success: test_delete_node')

def main():
test = TestDeleteNode()
test.test_delete_node()

if __name__ == '__main__':
main()

Overwriting test_delete_mid.py

In [4]:
%run -i test_delete_mid.py

Test: Empty list, null node to delete
Test: One node
Test: Multiple nodes
Test: Multiple nodes, delete last element
Success: test_delete_node