面试题18:删除链表的节点
题目描述:
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
解法一:双指针+特判
思路:
- 两个指针 pre 和 cur ,从链表头结点向后走,找到后将 cur 节点删除
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
if(head == nullptr) return nullptr;
if(head->next == nullptr || head->val == val)
{
head = head->next;
return head;
}
ListNode* cur = head->next;
ListNode* pre = head;
while(cur->val != val && cur->next != nullptr)
{
pre = cur;
cur = cur->next;
}
if(cur->val == val)
{
pre->next = cur->next;
delete cur;
cur = nullptr;
}
return head;
}
};
解法二:虚拟头结点+单指针
思路:
- 在头节点前面增加一个虚拟头结点,这样就省去了所有的特判
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
ListNode* vhead = new ListNode(0);
vhead->next = head;
ListNode* cur = vhead;
while(cur->next)
{
if(cur->next->val == val)
{
ListNode* tmp = cur;
cur = cur->next;
tmp->next = cur->next;
break;
}
cur = cur->next;
}
return vhead->next;
}
};