leetcode--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:
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.
我的思路:
这是个单向链表,无法得知node的上一个节点是谁;
node的val用node.next.val代替,然后node.next指向node.next.next,这样即使是单向链表,删除节点还是不会断。
代码实现:
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ nextnode = node.next node.val = nextnode.val node.next = nextnode.next