美文网首页《剑指offer》Python版
18-1在O(1)时间删除链表结点

18-1在O(1)时间删除链表结点

作者: gantrol | 来源:发表于2019-01-17 14:39 被阅读0次

    给定单向链表的头指针和一个结点指针,定义一个函数在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!'
    

    相关文章

      网友评论

        本文标题:18-1在O(1)时间删除链表结点

        本文链接:https://www.haomeiwen.com/subject/wxjidqtx.html