leetcode with python:237. Delete Node in a Linked List

题目:

Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.

It is guaranteed that the node to be deleted is not a tail node in the list.

给定一个在linked list内部的Node,将其删除,该Node不会是尾端的Node

这题刚看到满是困惑
心想没给我该Node的上一个Node我该怎么删掉它
后来我想到,万一我们删掉的不是这个Node呢?

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    def deleteNode(self, node):        """        :type node: ListNode        :rtype: void Do not return anything, modify node in-place instead.        """        node.val=node.next.val        node.next=node.next.next

既然题目确保了我们的下一个Node不会是None
那我们乾脆删掉我们下一个Node,用现在这个Node纪录删掉那个Node的值
所以将该Node的值改为下一个Node的值
next直接接到下下个Node
一个没有该Node的linked list就大功告成了
最后执行时间35ms(faster than 98.11%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章