# 237. Delete Node in a Linked List

98人阅读 评论(0)

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) {
if (node == null) {
return;
}
if (node.next == null) {
node = null;
return;
}
node.val = node.next.val;
node.next = node.next.next;
}
}

python

"""
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):
if node is None:
return
if node.next is None:
node = None
return
node.val = node.next.val
node.next = node.next.next


个人资料
等级：
访问量： 22万+
积分： 8246
排名： 3014
最新评论