ループポインタ実装スタック


`
class MyCircularQueue {

    var queue: [Int] = []
    var k: Int = 0
    var start = 0
    var end = 0
    var isFullVal: Bool = false
    
    /** Initialize your data structure here. Set the size of the queue to be k. */
    init(_ k: Int) {
        self.k = k
        self.queue = Array.init(repeating: 0, count: k)
    }
    
    /** Insert an element into the circular queue. Return true if the operation is successful. */
    func enQueue(_ value: Int) -> Bool {
        if !isFull() {
            queue[end] = value
            end += 1
            if end == k {
                end -= k
            }
            if end == start {
                isFullVal = true
            }
            return true
        } else {
            return false
        }
        
    }
    
    /** Delete an element from the circular queue. Return true if the operation is successful. */
    func deQueue() -> Bool {
        if !isEmpty() {
            if isFullVal {
                isFullVal = false
            }
            start += 1
            if start == k {
                start -= k
            }
            return true
        } else {
            return false
        }
    }
    
    /** Get the front item from the queue. */
    func Front() -> Int {
        if isEmpty() {
            return -1
        } else {
            return queue[start]
        }
    }
    
    /** Get the last item from the queue. */
    func Rear() -> Int {
        if isEmpty() {
            return -1
        } else {
            return end == 0 ? queue[k - 1] : queue[end - 1]
        }
    }
    
    /** Checks whether the circular queue is empty or not. */
    func isEmpty() -> Bool {
        return isFullVal ? false : start == end
    }
    
    /** Checks whether the circular queue is full or not. */
    func isFull() -> Bool {
        return isFullVal
    }
    
    func count() -> Int {
        if end > start {
            return end - start + 1
        } else {
            return k - abs(start - end)
        }
        
    }
    
    func movingAverage(_ i: Int, _ j: Int) -> Double {
        let m = count()
        if (i >= 0 && j >= i && j < m) {
            var sum = 0
            for x in 0...j - i {
                var index = start + i + x
                if index == k {
                    index = index - k
                }
                sum += queue[index]
                print(sum)
            }
            return Double(sum) / Double(j - i  + 1)
        }
        return -1
    }
}


let c = MyCircularQueue.init(4)
print(c.enQueue(3))
print(c.enQueue(1))
print(c.enQueue(2))
print(c.enQueue(3))
print(c.Rear())
print(c.isFull())
print(c.deQueue())
print(("\(c.start) \(c.end)"))
print(c.enQueue(4))
print(("\(c.start) \(c.end)"))
print(c.isFull())
print(c.Rear())
print(c.movingAverage(2, 3))

`