-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdelete_node.py
More file actions
57 lines (39 loc) · 1.2 KB
/
delete_node.py
File metadata and controls
57 lines (39 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
Delete a node from a singly-linked list, ↴ given only a variable pointing to that node.
The input could, for example, be the variable b below:
class LinkedListNode(object):
def __init__(self, value):
self.value = value
self.next = None
a = LinkedListNode('A')
b = LinkedListNode('B')
c = LinkedListNode('C')
a.next = b
b.next = c
delete_node(b)
"""
class SinglyLinkedList:
def __init__(self):
self.head = None
def add_node_to_list(self, value):
"""Adds a new node to the SLL"""
if not self.head:
self.head = Node(value)
else:
current = self.head
while current.next:
current = current.next
current.next = Node(value)
class Node:
def __init__(self, value):
self.value = value
self.next = None
def delete_node(node):
"""Takes in a node and deletes it from a chain where it is not the end node"""
if not node.next:
raise Exception("Node must not be the end of the list")
next_node = node.next
node.value = next_node.value
node.next = next_node.next
# Allows garbage collection of node with no reference/use
next_node.next = None