方法一:双指针:时间O(n),空间O(1)
题解:
- 用两个指针,pre 代表前驱节点,cur 表示当前节点。
- 遍历链表如果 cur 值和 target 相等则让 cur 的前驱指向cur 的后继
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val)
{
1.双指针
if (head == NULL)
return head;
if (head->val == val)
return head->next;
ListNode* pre = head, * cur = head->next;
while (cur != nullptr && cur->val != val)
{
cur = cur->next;
pre = pre->next;
}
if (cur != nullptr)
{
pre->next = cur->next;
}
return head;
}
};
方法二:单指针:时间O(n),空间O(1)
题解:单指针的思路和双指针一样,需要对头结点先进行判断
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val)
{
if (head == nullptr)
return head;
if (head->val == val)
return head->next;
ListNode* cur = head;
while (cur->next != nullptr && cur->next->val != val)
{
cur = cur->next;
}
if (cur->next != nullptr)
cur->next = cur->next->next;
return head;
}
};