Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4
and you are given the third node with value 3
, the linked list should become 1 -> 2 -> 4
after calling your function.
java
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/*
* @param node: the node in the list should be deletedt
* @return: nothing
*/
public void deleteNode(ListNode node) {
// write your code here
if (node == null) {
return;
}
if (node.next == null) {
node = null;
return;
}
node.val = node.next.val;
node.next = node.next.next;
}
}
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: node: the node in the list should be deletedt
@return: nothing
"""
def deleteNode(self, node):
# write your code here
if node is None:
return
if node.next is None:
node = None
return
node.val = node.next.val
node.next = node.next.next