剑指offer删除链表节点(C++代码实现+用例)
#include<iostream>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
if(head==NULL)
{
std::cout <<"this is ListNode is empty !"<<std::endl;
return nullptr;
}
else if(head->val==val)
{
head = head->next;
return head;
}
ListNode* p_head = head;
while(p_head->next != NULL&&p_head->next->val!=val)
{
p_head = p_head->next;
}
p_head->next = p_head->next->next;
return head;
}
};
int main()
{
//测试用例;
ListNode* head = new ListNode(4);
ListNode* sec = new ListNode(1);
ListNode* thr = new ListNode(5);
ListNode* fou = new ListNode(9);
head->next = sec;
sec->next = thr;
thr->next = fou;
fou->next = NULL;
Solution s;
s.deleteNode(head,5);
while(head!=nullptr)
{
std::cout <<head->val<<std::endl;
head = head->next;
}
}