H.y's Blog



H.y's Blog

10.1-6

Q:说明如何用两个栈来实现一个队列,并分析有关队列操作的运行时间。

A:栈是先进后出,而队列是先进先出,一种自然的想法是,用一个栈来存储队列的元素,入队就和如栈一样; 出队的时候先将这个栈的元素依次压出另一个栈内,然后将栈顶元素(即队首)弹出,然后再依次倒回原先的栈内。 这样入队为O(1),出队为O(n)。仔细想想,并不需要每次都将当前所有元素在两个栈内倒来倒去, 只需要入队用一个栈,出队用另一个栈: 入队操作即在第一个栈上执行入栈;出队操作时,若第二个栈不为空,则在第二个栈上执行出栈, 若第二个栈为空,则将第一个栈内的元素依次全部压入第二个栈内。这样入队出队操作都为O(1)的复杂度。

10.1-7

Q:说明如何用两个队列来实现一个栈,并分析有关栈操作的运行时间。

A:一种自然的想法,类似于上一题,用一个队存储,另一个队列作为临时空间。入栈时就向第一个队列中插入元素; 出栈时,先将第一个队列中除队尾(栈顶)的元素依次出队后进入第二个队列,然后将队尾(栈顶 ...

more…


Read full article from H.y's Blog


No comments:

Post a Comment

Labels

Algorithm (219) Lucene (130) LeetCode (97) Database (36) Data Structure (33) text mining (28) Solr (27) java (27) Mathematical Algorithm (26) Difficult Algorithm (25) Logic Thinking (23) Puzzles (23) Bit Algorithms (22) Math (21) List (20) Dynamic Programming (19) Linux (19) Tree (18) Machine Learning (15) EPI (11) Queue (11) Smart Algorithm (11) Operating System (9) Java Basic (8) Recursive Algorithm (8) Stack (8) Eclipse (7) Scala (7) Tika (7) J2EE (6) Monitoring (6) Trie (6) Concurrency (5) Geometry Algorithm (5) Greedy Algorithm (5) Mahout (5) MySQL (5) xpost (5) C (4) Interview (4) Vi (4) regular expression (4) to-do (4) C++ (3) Chrome (3) Divide and Conquer (3) Graph Algorithm (3) Permutation (3) Powershell (3) Random (3) Segment Tree (3) UIMA (3) Union-Find (3) Video (3) Virtualization (3) Windows (3) XML (3) Advanced Data Structure (2) Android (2) Bash (2) Classic Algorithm (2) Debugging (2) Design Pattern (2) Google (2) Hadoop (2) Java Collections (2) Markov Chains (2) Probabilities (2) Shell (2) Site (2) Web Development (2) Workplace (2) angularjs (2) .Net (1) Amazon Interview (1) Android Studio (1) Array (1) Boilerpipe (1) Book Notes (1) ChromeOS (1) Chromebook (1) Codility (1) Desgin (1) Design (1) Divide and Conqure (1) GAE (1) Google Interview (1) Great Stuff (1) Hash (1) High Tech Companies (1) Improving (1) LifeTips (1) Maven (1) Network (1) Performance (1) Programming (1) Resources (1) Sampling (1) Sed (1) Smart Thinking (1) Sort (1) Spark (1) Stanford NLP (1) System Design (1) Trove (1) VIP (1) tools (1)

Popular Posts