The title
Implement a queue with two stacks. Implement appendTail and deleteHead to insert an integer at the end of the queue and delete an integer at the head of the queue. (If there are no elements in the queue, the deleteHead operation returns -1)
Example 1: input: [" CQueue ", "appendTail", "deleteHead", "deleteHead"] [[], [3], [], []] output: [3, null, null, 1] example 2: input: [" CQueue deleteHead ", ""," appendTail ", "appendTail", "deleteHead", "deleteHead"] [[], [], [5], [2], [], []] output: [null, 1, null, null, 5, 2]Copy the code
Tip:
1 <= values <= 10000 Calls to appendTail and deleteHead are performed at most 10000 times
Their thinking
class CQueue { var inputList:[Int] = [] var outputList:[Int] = [] init() { } func appendTail(_ value: Int) {inputList.appEnd (value)} func deleteHead() -> Int {// Put inputList in outputList and unstack if outputList.isEmpty == true { while inputList.isEmpty == false { outputList.append(inputList.popLast()!) } if outputList.isEmpty == false { return outputList.popLast()! } else { return -1 } } else { return outputList.popLast()! } } } /** * Your CQueue object will be instantiated and called as such: * let obj = CQueue() * obj.appendTail(value) * let ret_2: Int = obj.deleteHead() */ let obj = CQueue() obj.appendTail(5) obj.appendTail(4) let ret_2: Int = obj.deleteHead() obj.appendTail(3) let ret_3: Int = obj.deleteHead()Copy the code