Java data structures and algorithms-stacks and queues

Source: Internet
Author: User
Tags arithmetic


Q: What is the difference between stacks, queues, and arrays?


A: This article mainly involves three kinds of data storage types: Stack, queue and priority queue, it has the following three differences with the array:



A: (i) Programmer tools
Arrays and other structures (stacks, queues, linked lists, trees, and so on) are used in database applications as data records. They are often used to record data that corresponds to real-world objects and activities, such as employee profiles, which facilitate access to data: they are easy to insert, delete, and find operations on specific data items.
However, the data structures and algorithms to be explained in this article are more used as programmers ' tools. They are primarily used as an aid to the idea of algorithms, rather than as a complete data storage tool. The life cycle of these data structures is much shorter than the structure of those database types. They are created during the execution of a program operation, usually using them to perform a particular task, and when the task is completed, they are destroyed.



A: (ii) Restricted access
In the array, if you know the subscript of the data item, you can access the data item immediately, whereas in this data structure, access is restricted, that is, only one data item can be read or deleted at a particular time.
These structural interfaces are designed to enhance this limited access, and access to other data items is theoretically disallowed.



A: (iii) More abstract
Stacks, queues, and priority queues are more abstract structures than arrays and other data storage structures. Mainly through the interface to the stack, queue and Priority queue definition, interface shows what they can do, and the main implementation mechanism is not visible to the user.
For example: the implementation mechanism of the stack can be implemented in an array, this example is handled, but it can also be implemented with a linked list. The internal implementation of the priority queue can be implemented using an array or a special tree-heap.


Q: What is a stack?


A: the stack allows access to only one data item: That is, the last inserted data item. This data item is removed to access the second-to-last inserted data item, and so on.


Q: What are the actual scenarios on the stack?


A: Most microprocessors use a stack-based architecture, and when a method is called, its return value and parameters are pressed into the stack, and when the method finishes returning, which data is out of the stack. The stack operation is embedded in the microprocessor.


Q: Java code for stacks?


A: in this example, the type of the data item in the Stackx class is a long type, which is implemented by an array, and the top variable stores the subscript of the topmost element of the stack.



Example: Stackx.java, Stackxtest.java


Q: stack Example 1: reverse the word?


A: The first example of a stack is to do something very simple: reverse the word. The order of the letters is reversed because of the feature of the last-in-first-out (LIFO) of the stack.



Example: Reverser.java


Q: stack Example 2: Delimiter match?


A: stacks are usually used to match the left and right delimiters, because the last left delimiter needs to be matched first, which conforms to the characteristics of the stack's LIFO.
Here are some examples:


c[d]        // correct
a{b[c]d}e   // correct
a{b(c]d}e   // not correct; ] doesn’t match (
a[b{c}d]e}  // not correct; nothing matches final }
a{b(c)      // not correct; nothing matches opening {


The delimiter match program reads characters from the string continuously, reading one character at a time. If it is found to be a left delimiter, press it into the stack. When a right delimiter is read, the left delimiter at the top of the stack pops up, and you see if it matches the right delimiter. (Note: Non-delimiter characters are not inserted in the stack, just ignore them.) )



Example: Bracketchecker.java


Q: How efficient is the stack?


A: The stack that is implemented in the Stackx class, the time complexity of the stack and the stack is constant O (1), and the time spent on the stack operation does not depend on the number of data items in the stack, so the operation time is very short. Stacks do not require comparison and move operations.


Q: What is a queue?


A: queues (queue) in the dictionary is the meaning of "queue" (Waiting line). In computer science, a queue is a data structure that is somewhat similar to a stack, except that the first inserted data item in the queue is first removed (FIFO), whereas in the stack, the last inserted data item is first removed (LIFO).


Q: What is a cyclic queue?


A: in order to avoid queue dissatisfaction but can not insert new data items, you can let the team head tail pointer around the beginning of the array position, this is the loop queue.


Q: What are the actual scenarios for the queue?


A: use a word processor, tap a key, and the computer will do other things temporarily. The hit content will not be lost, it will wait in the queue, knowing that the word processing program has time to read it. The queue ensures that the order in which you type is processed does not change.


Q: What is the Java code for the queue?


A: The queue class has not only Mfront (team head) and mrear (tail), but also the number of current data items in the queue msize.



A: add/offer () method
Inserts the specified element into this queue. The difference is that add (e) throws an exception, and the Offer (e) returns a special value.



An internal call to the Insert () method, in general, inserts a new data item at the position indicated by the tail pointer when the insert operation Mrear (tail pointer) is added. However, when mrear points to the last element of the array, that is, the mitems.length-1 position, before inserting the data item, it must go back to the first element of the array, that is, Mrear is set to-1, so when Mrear adds 1, it equals 0, which is the subscript value of the first element of the array. Finally, Msize plus one.



A: Remove ()/poll () method
Gets and removes the header for this queue. The difference is that remove (e) throws an exception, and poll (e) returns a special value.



The extract () method is called internally, and the method always gets the value of the team header data item by the Mfront pointer, and then adds a mfront. However, if you do this mfront will exceed the size of the array, Mfront must go back to where the array is labeled 0. Note that the return value is temporarily stored first. Finally Msize minus one.



A: Peek () method
Gets the header of this queue without removing it, or returns null_element if this queue is empty.



A: Example: Queue.java


Q: Does the queue Java code for the data item count field be numbered?


A: including data item count fields in the queue class msize the Insert () and extract () methods to add a bit of extra action, because processing the insert () and remove () methods must increment and decrement the variable value, respectively. This may not be an additional overhead, but if you handle a large number of insertions and removal operations, this can affect performance. Therefore, some queue implementations do not use fields with data item counts, but rather mfront and mrear to calculate whether the queue is empty or full and the number of data items.



Example: Queue.java


Q: How efficient is the queue?


A: As with stacks, the time complexity of inserting and removing data items in a queue is O (1)


Q: Double-ended queue?


A: slightly


Q: Priority queue?


A: The priority queue is another queue that differs from the FIFO queue. The element with the highest priority is removed from the queue each time.


Q: What are the actual scenarios for the priority queue?


A: For example, in a preemptive multitasking operating system, programs are arranged in priority queues so that the highest priority programs get time slices and run.


Q: Java code for priority queue?


A: This example uses an ordered array to implement the priority queue, which is slower to insert, but it is relatively simple, and is suitable for situations where the amount of data is small and is not particularly focused on insertion speed.



Example: Priorityqueue.java



A: The minimum keyword is worth the data item always at the high end of the array (at the highest subscript value), and the largest data item is at the low end (where the subscript value is 0).



A: The data items for the team are always at the high end of the array, so the delete operation is quick and easy. After the data item is deleted, the team head pointer moves down to the new high end of the queue and does not need to be moved and compared.



A: Note that no pointer wraps around, and the tail pointer never moves, it always refers to the element at the low end of the array.



A: The font and rear pointers are intended to be compared to the normal queue and do not actually need them.



A: When the number of data items is relatively small, or less concerned about the speed of the case, the use of arrays to achieve the priority queue can also meet the requirements. If the data items are many, or the speed is important, the use of heaps is a better choice.


Q: What is the efficiency of the priority queue?


A: The priority queue insert operation for this example requires an O (N) time, while the delete operation requires an O (1) time. Later, you will learn how to improve the time of the insert operation through the heap.


Q: How do I parse an arithmetic expression?


A: for2*(3+4)arithmetic expressions such as or((2+4)*7)+3*(9-5), we've shown how to apply stacks to check if delimiters match correctly, but then we'll learn how to parse these arithmetic expressions.



In fact, it is quite difficult for a computer algorithm to find the value of an arithmetic expression directly, so it is easier for the algorithm to achieve this two-step implementation:
1. Converting an arithmetic expression to another form: suffix expression
2. Calculating the value of a suffix expression


Q: infix/suffix expression?


A: infix expression: The operator is placed between two operands. such as A+b or A/b.
A: suffix expression: Also known as the inverse Polish expression (Reverse Polish notation or RPN), it was invented by a Polish mathematician. The operator follows the two operands and does not contain parentheses. So a+b becomes ab+,a/b into ab/.



A: Here is an example of an infix expression converted to a suffix expression:


Q: How do people calculate infix expressions?


A: because of Mr. Klemmer's long-term teaching and learning, for 3+4+5 or the 4+5 expression, we humans do this problem is quite easy. By analyzing how humans calculate the values of these expressions, it is possible to derive the implications of converting to suffix expressions:
Roughly speaking, when parsing an arithmetic expression, the following rules should be followed:
1. Reading a calculation from left to right
2. It has been read that it is possible to calculate the number of two operands and an operator that can be calculated and replace the two operands and which operator with the result of the calculation.
3. Continue the process--from left to right, and even--until the end of the expression.



A: Example: 3 + 4-5






A: Example: 3 + 4 * 5



A: Example: 3 * (4 + 5)


Q: How can I convert infix expressions to postfix expressions?


A: As you can see earlier, the infix expression is evaluated both forward and backward. The rules for converting infix expressions to postfix expressions are similar to those for calculating infix expressions. But it's still a little bit different.



A: the infix expression is converted to a suffix expression without doing arithmetic operations, it does not seek the value of infix expression, just rearrange the operands and operators into another form.



A: conversion Rules:



A: Example: a+b-c



A: Example: A+b*c



A: Example: A * (B+C)


Q: is the infix expression converted to the Java code of the suffix expression?


A: Example: In2posttransform.java


Q: How do human beings evaluate with suffix expressions?


A: shows how humans calculate suffix expressions on paper by observing and pencils.
Example: 345+*612+/–



Starting with the first operator on the left, the two operands adjacent to its left are drawn in a circle, then the operator is applied to operate two operands and the result is written in the circle. The value in the largest circle is the final result of the expression.


Q: What are the rules for evaluating suffix expressions?


A: how can I write a program to repeat the evaluation process? As described above, with each operator encountered, it is used to calculate the last two operands seen before, which indicates that the stack can be used to store the operand. It has the following rules:



The result of the arithmetic operation is pressed into the stack, and after the last character (which must be the operator) is read and computed, only one data item is left in the stack, which is the result of the operation of the entire expression.


Q: What is the Java code for the suffix expression evaluation?


A: To simplify the code, you can only enter a single digit number here.
Example: Postfixparser.java


Q: Summary of this article?
    • Stacks, queues, and priority queues are data structures that are often used to simplify some program operations.
    • In these data structures, only one item of data can be accessed.
    • The stack only allows access to the last inserted data item.
    • The queue only allows access to the first inserted data item.
    • A queue can be implemented as a circular queue, which is based on an array, and the array subscript wraps around the end of the array to the beginning of the array.
    • The important operation of the priority queue is to insert new data items in an orderly manner and remove the smallest (and sometimes largest) data items of the keyword.
    • These data structures can be implemented in arrays or by other mechanisms, such as linked lists.
Q: Reference
      1. Java data structures and Algorithms Robert Lafore, chapter 4th-Stacks and queues


Java data structures and algorithms-stacks and queues


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.