美文网首页
[刷题防痴呆] 0203 - 移除链表元素 (Remove Li

[刷题防痴呆] 0203 - 移除链表元素 (Remove Li

作者: 西出玉门东望长安 | 来源:发表于2021-12-08 03:19 被阅读0次

    题目地址

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

    题目描述

    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
    
    

    思路

    • 如果当前位的下一位的val与所给val相等, 则跳过.

    关键点

    • 注意, 此题一开始要把head往前走一位, 因为要看下head是不是需要删除.

    代码

    • 语言支持: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) {
            if (head == null) {
                return head;
            }
            
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            head = dummy;
            
            while (head.next != null) {
                if (head.next.val == val) {
                    head.next = head.next.next;
                } else {
                    head = head.next;
                }
            }
            
            return dummy.next;
        }
    }
    

    相关文章

      网友评论

          本文标题:[刷题防痴呆] 0203 - 移除链表元素 (Remove Li

          本文链接:https://www.haomeiwen.com/subject/shioxrtx.html