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

题目链接

18. 删除链表的节点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        std::ios::sync_with_stdio(false);
        if(!head || !head->next) return head;
        auto dummy = new ListNode(-1);
        dummy->next = head;
        ListNode* p = dummy;
        while(p->next){
            if(p->next->val == val)
                p->next = p->next->next;
            else p = p->next;
        }
        auto res = dummy->next;
        delete dummy;
        return res;
    }
};
posted @ 2021-03-30 18:39  蒟蒻颖  阅读(25)  评论(0编辑  收藏  举报