Queue (Queue): It is a linear table that is limited to insertion at one end of the table and deletion at the other end;
Stack (Stack): Yes A linear table that restricts insertion and deletion operations to only one end of the table.
The differences are as follows:
1. Different rules
1. Queue: First In First Out (First In First Out) FIFO
2. Stack: First In Last Out (First In Last Out) FILO
2. Different restrictions on insertion and deletion operations
1. Queue: Insertion can only be done at one end of the table. And delete at the other end of the table;
2. Stack: You can only insert and delete at one end of the table.
3. Different data traversal speeds
1. Queue: Traverse based on address pointer, and can be traversed from the head or tail, but cannot be traversed at the same time. There is no need to open up space, because during traversal The data structure is not affected during the process, so the traversal speed should be faster;
2. Stack: Data can only be taken from the top, that is to say, the first thing to enter the bottom of the stack needs to traverse the entire stack to be taken out, and While traversing the data, it is necessary to open up temporary space for the data to maintain the consistency of the data before traversing.
4. Similarities and differences in interface implementation
The queue and stack are implemented by the Collection interface, the queue is implemented by the Queue interface, and the stack is implemented by the List interface.
5. Similarities and differences in data traversal speed
The stack can only take data from the head, that is, the first thing put in needs to traverse the entire stack before it can be taken out, and when traversing the data It is also necessary to open up temporary space for the data to maintain the consistency of the data before and after traversal.
The queue is traversed based on the address pointer, and can be traversed from the beginning or the end without opening up temporary space, which is much faster.
The above is the detailed content of What is the difference between stack and queue in java?. For more information, please follow other related articles on the PHP Chinese website!