[LeetCode] 203. 移除链表元素(Remove Linked List Elements)

本文已收录于 LeetCode刷题 系列,共计 28 篇,本篇是第 13 篇

本文已收录到:LeetCode刷题 专题

[title]题目[/title]

删除链表中等于给定值 val 的所有节点。

示例:

输入:

 1->2->6->3->4->5->6,

val

 = 6

输出:

 1->2->3->4->5

[title]视频讲解[/title]

[bilibili cid=”” page=”1″]200206789[/bilibili]

 

[title]简明思路[/title]

 

[title]代码[/title]

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode dummy(0);
        ListNode* tail = &dummy;
        tail->next = head;

        ListNode* cur = tail;

        while (cur->next != nullptr)
        {
            if (cur->next->val == val)
            {
                cur->next = cur->next->next;
            }
            else 
            {
                cur = cur->next;
            }
        }
        return dummy.next;
    }
};

 

作者: 高志远

高志远,24岁,男生

发表评论

邮箱地址不会被公开。