Skip to content

Latest commit

 

History

History
47 lines (40 loc) · 1.34 KB

203.remove-linked-list-elements.md

File metadata and controls

47 lines (40 loc) · 1.34 KB
// Delete the head, and move the head
[6, 6, 6, 1], value = 6 --> [1]

// Delete non-head node
[1, 2, 3, 3], value = 3 --> [1, 2]

When deleting a node, we can implement in the following way:

var previous: ListNode? = null
var current: ListNode? = head
while (current != null) {
    if (current == nodeToDelete) {
        previous?.next = current.next
    } else {
        previous = current
        current = current.next
    }
}

However, the implementation will not work when delete the head, since previous is null and previous?.next will not be executed at all, we have find other way to handle the case to delete head.

We introduce sentinel node to help us when deleting the head node so that we can implement node deletion in the above way even for deleting head.

fun removeElements(head: ListNode?, `val`: Int): ListNode? {
    val sentinel = ListNode(-1)
    sentinel.next = head
    // Here is different part.
    var previous: ListNode? = sentinel
    var current: ListNode? = head
    while (current != null) {
        if (current.`val` == `val`) {
            previous?.next = current.next
        } else {
            previous = current
        }
        current = current.next
    }
    return sentinel?.next
}