文章 224
评论 6
浏览 200762
LinkedList - 203. Remove Linked List Elements

LinkedList - 203. Remove Linked List Elements

203. 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(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) return head;
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode curr = dummy;
        while (curr != null && curr.next != null) {
            if (curr.next.val == val) curr.next = curr.next.next;
            else curr = curr.next;
        }
        
        return dummy.next;
    }
}

标题:LinkedList - 203. Remove Linked List Elements
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/07/28/1564323468866.html

Nothing just happens, it's all part of a plan.

取消