Using Figure 10.1 as a model, illustrate the result of each operation in the sequence PUSH(S, 4), PUSH(S, 1), PUSH(S, 3), POP(S), PUSH(S, 8), and POP(S) on an initially empty stack S stored in array S[1...6].
1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|
4 |
1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|
4 | 1 |
1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|
4 | 1 | 3 |
1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|
4 | 1 |
1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|
4 | 1 | 8 |
1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|
4 | 1 |
Explain how to implement two stacks in one array A[1...n] in such a way that neither stack overflows unless the total number of elements in both stacks together is n. The PUSH and POP operations should run in O(1) time.
分别从两头开始做就行了
Using Figure 10.2 as a model, illustrate the result of each operation in the sequence ENQUEUE(Q, 4), ENQUEUE(Q, 1), ENQUEUE(Q, 3), DEQUEUE(Q), ENQUEUE(Q, 8), and DEQUEUE(Q) on an initially empty queue Q stored in array Q[1...6].
1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|
4 |
1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|
4 | 1 |
1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|
4 | 1 | 3 |
1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|
1 | 3 |
1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|
1 | 3 | 8 |
1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|
3 | 8 |
Rewrite ENQUEUE and DEQUEUE to detect underflow and overflow of a queue.
在开头加上
ENQUEUE(Q, x):
if head[Q] == tail[Q] + 1
then error "overflow"
......
DEQUEUE(Q):
if head[Q] == tail[Q]
then error "underflow"
......
Whereas a stack allows insertion and deletion of elements at only one end, and a queue allows insertion at one end and deletion at the other end, a deque (double-ended queue) allows insertion and deletion at both ends. Write four O(1)-time procedures to insert elements into and delete elements from both ends of a deque constructed from an array.
我没有检查overflow和underflow,用N去判断就可以了.
Show how to implement a queue using two stacks. Analyze the running time of the queue operations.
这个题目也出现在leetcode
最坏情况pop需要O(n),但是pop的平均情况只需要O(1)
Show how to implement a stack using two queues. Analyze the running time of the stack operations.
- push操作是O(1)的
- empty操作是O(1)的
- top操作是O(1)的
- 但是pop操作最坏需要O(n)
Follow @louis1992 on github to help finish this task.