版权声明:本文未经博主允许不得转载。 https://blog.csdn.net/pianzang5201/article/details/91456031
问题:
给定一个单链表中的一个等待被删除的节点(非表头或表尾)。请在在 O(1) 时间复杂度删除该链表节点。
样例
样例 1:
输入: 1->2->3->4->null 3 输出: 1->2->4->null
样例 2:
输入: 1->3->5->null 3 输出: 1->5->null
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 deleted
@return: nothing
"""
def deleteNode(self, node):
# write your code here
if node == None:
return None
if node.next != None:
node.val = node.next.val
node.next = node.next.next
else:
node.next = None
C++:
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param node: the node in the list should be deleted
* @return: nothing
*/
void deleteNode(ListNode * node) {
// write your code here
if(node == NULL)
{
return;
}
if(node->next != NULL)
{
node->val = node->next->val;
node->next = node->next->next;
}else{
node->next = NULL;
}
}
};