Data Structure is a way to organize data. It provides some methods to handle data stream, e.g. insert, delete, etc.
First In First Out
The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.
In Java, there is a Queue Interface. Implemented by LinkedList, ArrayDeque, etc.
add: O(1) remove: O(1) peek: O(1)
Queue is often used when elements need to be processed First In First Out.
1) When a resource is shared among multiple consumers. Examples include CPU scheduling, Disk Scheduling.
2) When data is transferred asynchronously (data not necessarily received at same rate as sent) between two processes. Examples include IO Buffers, pipes, file IO, etc.
3) BFS
Example:
Implementing Queue Using Two Stacks
Priority Queue is an extension of queue with following properties.
1) Every item has a priority associated with it.
2) An element with high priority is dequeued before an element with low priority.
3) If two elements have the same priority, they are served according to their order in the queue.
In Java, PriorityQueue is a class.
Comparator
provided at queue construction time, depending on which constructor is used. Implementation of Priority Queue:
1. Use array
class node {
public int value;
public int priority;
}
2. Use heap
Application of Priority Queue
1) CPU Scheduling
2) Graph algorithms like Dijkstra’s shortest path algorithm, Prim’s Minimum Spanning Tree, etc
3) All queue applications where priority is involved.
Example
Allow insertion and deletion at both ends.
In Java, there is a Deque Interface. Implemented by ArrayDeque, LinkedList, ConcurrentLinkedDeque, LinkedBlockingDeque.
ArrayDeque:
LinkedList:
ConcurrentLinkedDeque:
Deque Application
Deque is often used in the problems where elements need to be removed and or added both ends.
Example: Sliding Window Maximum
Deque Implementation
A Deque can be implemented either using a doubly linked list or circular array. In both implementation, we can implement all operations in O(1) time.
原文:http://www.cnblogs.com/ireneyanglan/p/4907963.html