5.<Important> Delete Node in a Linked List

Title:

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.  !!!!!

Analysis of Title:

We needn't to analysis the title but the Note end that Do not return anything from your function.  

Test case:

[4,5,1,9]
5

Python:

class Solution(object):
  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

Analysis of Code:

This is the content of the linked list. 

The algorithm is: 

  1.[4,5,1,9]-->>[4,1,1,9]

  2.[4,1,1,9]-->>[4,1,9]

Notice: node.next means ponit next node, just like 5->1, so node.next.next means 5->->9.

 .next is a 'point', not a certain value, Originally I thought node.next is 1, so node.next = node.next.next means 5=9, it's wrong.

原文地址:https://www.cnblogs.com/sxuer/p/10628971.html