题目描述:
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.
代码实现(大神版):
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution: 8 def deleteNode(self, node): 9 """ 10 :type node: ListNode 11 :rtype: void Do not return anything, modify node in-place instead. 12 """ 13 node.val = node.next.val 14 node.next = node.next.next
分析:
关于用Python实现链表的知识详见:https://www.cnblogs.com/kumata/p/9147077.html
题目的要求是给定一个节点(该节点不在链表的尾部),将该节点删除掉。
实现思路非常简单:只需要用下一个节点来覆盖要删除的节点即可,也就是让当前节点的内容等于下一个节点的内容,同时让当前节点的指针指向下一个节点的指针即可。
如果给出的不是一个节点,而是给出节点中的内容,让删除这个节点,则一种代码实现方式如下:(个人版)
1 class ListNode: 2 def __init__(self, x): 3 self.val = x 4 self.next = None 5 6 class Solution: 7 def deleteNode(self, node): 8 """ 9 :type node: ListNode 10 :rtype: void Do not return anything, modify node in-place instead. 11 """ 12 a = ListNode(9) 13 b = ListNode(1) 14 c = ListNode(5) 15 d = ListNode(4) 16 17 b.next = a 18 c.next = b 19 d.next = c 20 head = d 21 22 fpointer, bpointer = head, head 23 while True: 24 if fpointer.val == node: 25 if fpointer == head: 26 head.val = fpointer.next.val 27 head.next = fpointer.next.next 28 elif fpointer.next == None: 29 bpointer.next = None 30 else: 31 bpointer.next = fpointer.next 32 bpointer.next.val = fpointer.next.val 33 break 34 else: 35 bpointer = fpointer 36 fpointer = fpointer.next 37 38 pointer = head 39 aa = [0] * 3 40 i = 0 41 while i < 3: 42 aa[i] = pointer.val 43 pointer = pointer.next 44 i += 1 45 print(aa) 46 47 if __name__ == '__main__': 48 Solution().deleteNode(9)