18-1在O(1)时间删除链表结点
2019-01-17 本文已影响0人
gantrol
给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点。
class Node:
def __init__(self, val, nxt=None):
self.value = val
self.next = nxt
class Node_list:
def __init__(self, begin=None):
self.begin = begin
def delete_node(lyst, aim_node):
if lyst is None or lyst.begin is None or lyst.begin.value is None or \
aim_node is None or aim_node.value is None:
return 'Wrong!'
# begin
if lyst.begin is aim_node:
lyst.begin = lyst.begin.next
return 'Success'
# middle
elif aim_node.next:
aim_node.value = aim_node.next.value
aim_node.next = aim_node.next.next
return 'Success'
# end
else:
probe = lyst.begin
while probe:
if probe is aim_node:
probe.next = None
return 'Success'
probe = probe.next
if __name__ == '__main__':
a = Node('a')
b = Node('b', a)
c = Node('c', b)
d = Node('d', c)
void = Node(None)
lyst = Node_list(d)
lyst_void = Node_list(void)
assert delete_node(lyst, c) == 'Success'
assert delete_node(lyst, d) == 'Success'
assert delete_node(lyst, a) == 'Success'
assert delete_node(None, None) == 'Wrong!'
assert delete_node(lyst_void, c) == 'Wrong!'
assert delete_node(lyst, void) == 'Wrong!'