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
    }

}

 

posted @ 2019-06-20 13:12  johnny_zhao  阅读(90)  评论(0编辑  收藏  举报