访问单个结点的删除 牛客网 程序员面试金典 C++ Python
访问单个结点的删除 牛客网 程序员面试金典 C++ Python
-
题目描述
-
实现一个算法,删除单向链表中间的某个结点,假定你只能访问该结点。
-
给定待删除的节点,请执行删除操作,若该节点为尾节点,返回false,否则返回true
C++
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Remove {
public:
//run:2ms memory:480k
bool removeNode(ListNode* pNode) {
if(NULL == pNode) return false;
if(NULL == pNode->next) return false;
ListNode* pNext = pNode->next;
pNode->val = pNext->val;
pNode->next = pNext->next;
free(pNext);
return true;
}
};
Python
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Remove:
#run:37ms memory:5740k
def removeNode(self, pNode):
if None == pNode: return False
if None == pNode.next:return False
pNext = pNode.next
pNode.val = pNext.val
pNode.next = pNext.next;
return True