# 237. Delete Node in a Linked List

81人阅读 评论(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


1
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：138030次
• 积分：6831
• 等级：
• 排名：第3864名
• 原创：553篇
• 转载：36篇
• 译文：5篇
• 评论：53条
最新评论