题解 | #从单向链表中删除指定值的节点#

从单向链表中删除指定值的节点

http://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f

个人认为是比较简洁的Python代码

class Node(object):
    def __init__(self, item):
        self.item = item
        self.next = None

class LinkedList(object):
    def __init__(self, item):
        self.head = Node(item)
        self.length = 1
    
    def insert(self,a , b):
        node_a = Node(a)
        node_b = Node(b)
        tmp = self.head
        while tmp != None:
            if tmp.item == node_b.item:
                node_a.next = tmp.next
                tmp.next = node_a
                self.length += 1
            tmp = tmp.next
    def delete(self,value):
        tmp = self.head
        while tmp.next != None:
            if tmp.next.item == value:
                tmp.next = tmp.next.next
            tmp = tmp.next
    def print_list(self):
        tmp = self.head
        while tmp is not None:
            print(tmp.item,end=' ')
            tmp = tmp.next
if __name__  == '__main__':
    list_input = list(map(int,input().split()))
    n = list_input[0]
    linkList = LinkedList(list_input[1])
    insert_list = list_input[2:-1]
    delete_node = list_input[-1]
    for i in range(0,len(insert_list),2):
        linkList.insert(insert_list[i], insert_list[i + 1])
    linkList.delete(delete_node)
    linkList.print_list()
全部评论

相关推荐

牛客5655:其他公司的面试(事)吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务