203. Remove Linked List Elements*

203. Remove Linked List Elements*

https://leetcode.com/problems/remove-linked-list-elements/

题目描述

Remove all elements from a linked list of integers that have value val.

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

C++ 实现 1

虚拟节点的使用. 如果遇到不等于 val 的节点, 就加入到 dummy 中.

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode *dummy = new ListNode(0);
        auto p = dummy;
        while (head) {
            if (head->val != val) {
                p->next = head;
                p = p->next;
            } 
            head = head->next;
        }
        p->next = nullptr;
        return dummy->next;
    }
};
发布了455 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/105010931
今日推荐