Stack & Queue Outline
1. Stack Introduction
2. Queue Introduction
3. Example Analysis
Stack
A stack is a container of objects that was inserted and removed according to the last-in first-out (LIFO) principle
Operations:push O (1), Pop O (1), Top O (1)
Use of stacks
Stack can be used as a helper to implement a depth first search, DFS, or recursive to a while loop (Depth)
Recursion itself is equivalent to adding a layer of the function itself to the operating system's memory stack, the stack operation is equivalent to recursive call itself, the stack operation is equivalent to recursive return.
Toolbox: C + +
Stack and queue:
BOOL Const // Returns Whether the stack is empty:i.e. Whether it size is zero. void push (const// inserts a new element at the top of the stack. The content of this new element was initialized to a copy of Val. void // removes the element on top of the stack, effectively reducing it size by one. // Returns A reference to the top element in the stack
View Code
Example:
stack<int>Mystack;mystack.push (Ten); Mystack.push ( -);intValue = Mystack.top ();//value equals toqueue<int>Myqueue;myqueue.push (Ten); Myqueue.push ( -);//queue now has both elements, the value of which is ten,intValue = Myqueue.front ();//value equals to tenMyqueue.pop ();//Queue now have one element, the value of which is
View Code
Queue
A queue is a container of objects (a linear collection) that's inserted and removed according to the first-in first-out (FIFO) principle
Operations:o (1) push,o (1) pop,o (1) Top
Always used for BFS
Use
We can use Queue as an aid to achieve the breadth-first algorithm (breadth-search, BFS)
The Queue can also be used as a buffer to build a producer-consumer model: The producer adds new elements to the end of the queue and the consumer reads the elements from the team's head. Synchronization (synchronization) is required when there are two threads reading the same queue at the same time
Stack and queue can be seen as packaged Linked lists, only restricting access and insertion freedom. For scenarios where a stack or queue is appropriate, consider using a more powerful list.
Pattern recognition
1. Special sequential reads via stack because the stack has a LIFO feature, if you want to implement read operations in any particular order, you can often use two stacks to "dump" each other to achieve a particular order. Another stack as an aid.
Get Max Stack
Implement a stack, enable O (1) Push, Pop Top, Max. Where Max () would return the value of maximum number in the stack.
Answer
Using the stacks.
The first one is the regular stack. The second one only store maximum numbers if a larger number comes.
Complexity analysis: Time complexity meets the requirements of the topic O (1). Space complexity The worst case is that each element needs to be stored in an additional stack, so an additional O (n) space is used.
Algorithm principles and practices (stacks and queues)