实现一个算法,删除单向链表中间的某个结点,假定你只能访问该结点。
给定带删除的头节点和要删除的数字,请执行删除操作,返回删除后的头结点。链表中没有重复数字。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Remove {
public:
ListNode* removeNode(ListNode* pHead, int delVal) {
// write code here
if (pHead->val == delVal) {
ListNode *node = pHead->next;
pHead->next = NULL;
return node;
}
ListNode *previous = pHead;
ListNode *current = pHead->next;
while (current != NULL) {
if (current->val == delVal) {
previous->next = current->next;
current->next = NULL;
}
previous = previous->next;
current = current->next;
}
return pHead;
}
};