剑指 Offer 18. 删除链表的节点

描述

给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。

tags: recursive, double pointer

思路

  1. 递归
class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        if(head == NULL){
            return head;
        }
        if(head->val == val){
            return head->next;  // val unique
        }
        head->next = deleteNode(head->next, val);
        return head;
    }
};
  1. 遍历
    利用val node 唯一的性质
class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        if(!head) return head;
        if(head->val == val) return head->next;
        ListNode* node = head;
        // find next.val == val
        while(node->next && node->next->val != val){
            node = node->next;
        }
        // shortcut val node
        if(node) node->next = node->next->next;
        return head;
    }
};