237. Delete Node in a Linked List删除链接列表中的节点

[抄题]:

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Given linked list -- head = [4,5,1,9], which looks like following:

Example 1:

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.

Example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.

Note:

  • The linked list will have at least two elements.
  • All of the nodes' values will be unique.
  • The given node will not be the tail and it will always be a valid node of the linked list.
  • Do not return anything from your function.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

  1. 链表这种结构,似乎总是需要先设置退出的情况

[思维问题]:

不知道输入参数就一个变量,该怎么删除。其实就是自己命名下一个节点就行了

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

其实是把node下一个节点的值拿过来用,下一个节点删掉,node自己不删,自带主角光环

这也是本题特殊的一个思维技巧吧。

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 节点的值也需要取代掉

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[算法思想:迭代/递归]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

猜你喜欢

转载自www.cnblogs.com/immiao0319/p/12927118.html