Thursday, September 15, 2016

remove, remove-all in linked list

remove(v):
    if head == null:
        throw
    if head.value == v:
        head = head.next
        return true
    n = head
    while n.next != null:
        if n.next.value == v:
            n.next = n.next.next
            result = true
            break
        n = n.next
    return result

removeall(v):
    if head == null:
        throw
    count = 0
    while head != null && head.value == v:
        head = head.next
        count++
    if head != null:
        n = head
        while n.next != null:
            if n.next.value == v:
                n.next = n.next.next
                count++
            else:
                n = n.next
    return count
[Hat tip to MK]

No comments:

Post a Comment