Leetcode P0203"Remove Linked List Elements" 题解

2020/10/13 Leetcode

博文中会简要介绍Leetcode P0203题目分析及解题思路。

“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

以下是Java的题解代码实现。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(0, head);
        ListNode prev = dummy, curr = head;
        while (curr != null) {
            if (curr.val == val) 
                prev.next = curr.next;
            else 
                prev = curr;
            
            curr = curr.next;
        }
        
        return dummy.next;
    }
}

以下是C++的题解代码实现。

/**
 * 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(0, head);
        ListNode *prev = dummy, *curr = head;
        while (curr) {
            if (curr->val == val) {
                prev->next = curr->next;
            }
            else {
                prev = curr;
            }
            
            curr = curr->next;
        }
        
        return dummy->next;
    }
};

Search

    Table of Contents