What is the running time of the translation of infix to postfix using queue and stack?

有些话、适合烂在心里 提交于 2019-12-24 00:57:46

问题


In c++... I know the time complexities for the individual functions of queue and stack, but I don't know what the time complexity for an infixToPostfix function would be, using both queue and stack....I am a beginner programmer of course, and I am very confused.


回答1:


Converting from infix to postfix using a stack and a queue is, I assume, Dijkstra's shunting-yard algorithm. One way to measure the complexity is to think about how many pushes and pops are done:

  • Every number is pushed exactly once and popped exactly once.
  • Every operator is pushed exactly once and popped exactly once.
  • Every token is dequeued from the queue of tokens exactly once.
  • Every intermediate result is pushed exactly once and popped exactly once.

If your string has length n, then it has O(n) numbers and O(n) operators, so the amount of work done by the first three of these groups in total would be O(n). To analyze the last group, note that each intermediate value comes from combining together two earlier values. If there are a total of O(n) numbers in the original input, this means that there can be O(n) values produced as intermediaries. Therefore, the total runtime would be O(n).

Converting from postfix to infix can similarly be shown to run in O(n) time using a argument like the one above.

Hope this helps!



来源:https://stackoverflow.com/questions/5305215/what-is-the-running-time-of-the-translation-of-infix-to-postfix-using-queue-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!