Thursday, March 26, 2015

circular stack

Used for undo operations.
circular-stack:
    a, capacity
    count = 0
    top = 0
    circular-stack(capacity):
        capacity = capacity
        a = new [capacity]
        
    push(x):
        a[top] = x
        top = wrapIndex(top +1, capacity)
        if count < capacity:
            count++
    x pop():
        if isempty():
            throw
        top = wrapIndex(top -1, capacity)
        count--
        return a[top]
    x peek():
        if isempty():
            throw
        return a[wrapIndex(top -1, capacity)]
    isempty():
        return count == 0
    count():
        return count
    clear():
        top = count = 0
    foreach():
        tos = top
        for i = 0, i < count, i++:
            tos = wrapIndex(tos -1, capacity)
            yield a[tos]
    
    wrapIndex(i, n):
        index = i %n
        if index < 0:
            index += n
        return index

[Hat tip to 2048]

No comments:

Post a Comment