返回

[Leetcode]203. Remove Linked List Elements(C++)

题目描述

题目链接:203. Remove Linked List Elements

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

例子

例子 1

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

解题思路

一次遍历,遇到下一个节点值为目标值时重新指向该节点的下一个节点并进行检查即可。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode* dummy = new ListNode();
        dummy->next = head;
        ListNode *curr = dummy;
        while (curr && curr->next) {
            while (curr->next && curr->next->val == val) {
                curr->next = curr->next->next;
            }
            curr = curr->next;
        }
        return dummy->next;
    }
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

GitHub 代码同步地址: 203.RemoveLinkedListElements.cpp

其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions

Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy