python3 链表中删除指定值的节点

class LNode:
    def __init__(self, elem, next_=None):
        self.elem = elem
        self.next = next_

def AddToTail(head, elem):
    if type(head) is not LNode and head is not None:#如果head的类型不是LNode且head不是None,则直接返回,不做处理
        print("+++++++++++++++++++++++++++++")
        return None
    if head is None:                                #链表为空
        head = LNode(elem)
    else:                                           #链表已经存在,直接插入
        p = head
        while p.next is not None:
            p = p.next
        p.next = LNode(elem)
    return head


def DeleteValue(head, elem):
    if head is None or type(head) is not LNode:    #链表为空或者提供的head的类型和LNode不一致
        if head is None:
            print("the list is invalid, head = ", head)
            return None
        elif type(head) is not LNode:
            print("wrong type, type = ", type(head))
            return None
    p = head
    while head.elem == elem:                       #如果链表的第一个元素为elem,需要删除
        head = head.next                           #站在本节点的角度删除本节点,此时head已经变为原head.next
        if head is None:                           #删除时可能出现把整个链表删光的情况
            break
    return_head = head                             #记录头节点
    if return_head is None:
        return return_head
    while head.next is not None:
        while head.next.elem == elem:              #站在当前节点删除下一跳节点
            head.next = head.next.next
            if head.next == None:                  #如果已经到达最后一个节点,停止迭代
                return return_head
        head = head.next
    return return_head



head = None

if __name__ == "__main__":

    '''
测试一:1 2 2 2 2 3 4 5
    head = AddToTail(head, 1)
    for i in range(4):
        head = AddToTail(head, 2)
    for i in range(3):
        head = AddToTail(head, i+3)
    '''
    '''
测试二: 2 2 3 4 5
    for i in range(2):
        head = AddToTail(head, 2)
    for i in range(3):
        head = AddToTail(head, i+3)
    '''
    '''
测试三: head = []
    '''
    '''
测试四: head = None
    '''
    p = head
    print("============")
    while p is not None:
        print(p.elem)
        p = p.next
    print("============")
    head = DeleteValue(head, 2)
    p = head
    while p is not None:
        print(p.elem)
        p = p.next

你可能感兴趣的:(数据结构,剑指offer,python实现)