203. Remove Linked List Elements

/***
 * 203. Remove Linked List Elements
 * https://leetcode.com/problems/remove-linked-list-elements/description/
 *
 * Remove all elements from a linked list of integers that have value val.
 */
class ListNode(var `val`: Int) {
    var next: ListNode? = null
}

class Solution {
    fun removeElements(head: ListNode?, value: Int): ListNode? {
        //help by 2 pointer: dummy, pre
       val dummy = ListNode(-1)//fake head
        var pre = dummy
        dummy.next = head
        while (pre.next!=null) {
            if (pre.next!!.`val` == value) {
                pre.next = pre.next!!.next
            } else {
                pre = pre.next!!
            }
        }
        return dummy.next
    }

}
原文地址:https://www.cnblogs.com/johnnyzhao/p/11058140.html