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

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

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

class NodeList:
	"""定义节点"""
    def __init__(self, val):
        self.val = val
        self.next = None


class LinkList:
    """定义链表"""

    def __init__(self, head: NodeList) -> None:
		# 初始化链表 
        self.head = head

    def add_node(self, m: int, n: int):
		# 添加链表节点
        cur = self.head
        node = NodeList(n)
        while cur:
            if cur.val == m:
                node.next = cur.next
                cur.next = node
                break
            else:
                cur = cur.next

    def remove_node(self, data: int):
        # 删除链表节点
        pre = None
        cur = self.head
        while cur:
            if cur.val == data:
                if not pre:
                    self.head = cur.next
                    break
                else:
                    pre.next = cur.next
                    break
            else:
                pre = cur
                cur = cur.next

    def get_node(self):
        # 获取链表数据
        cur = self.head
        while cur:
            print(cur.val, end=" ")
            cur = cur.next

while True:
    try:      
        lst = list(map(int, input().split(" ")))
        head = NodeList(lst[1])
        nl = LinkList(head)
        for i in range(1,len(lst[2:-1]),2):
            m = lst[2:-1][i]
            n = lst[2:-1][i-1]
            nl.add_node(m,n)
        nl.remove_node(lst[-1])
        nl.get_node()
    except:
        break




全部评论

相关推荐

10-24 11:10
山西大学 Java
若梦难了:哥们,面试挂是很正常的。我大中厂终面挂,加起来快10次了,继续努力吧。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务