Interview Questions set-stack and queue

Source: Internet
Author: User

How to prepare:

Whether you are asked to implement a simple stack/queue, or you are asked to implementa modified version of one, you will have a big leg up on other candidates if you can flawlessly work with stacks and queues practice makes perfect! Here is some
Skeleton code for a stackand queue class

When the interviewer needs you to implement a simple stack or line up, you can finish writing smoothly, then you are one step ahead of the average candidate. Familiar with the following basic stack and queue frameworksCodeBe sure to master.

Implementing a stack

Stack

1 class Stack {2 node top; 3 node POP () {4 If (top! = NULL) {5 object item = top. data; 6 Top = top. next; 7 return item; 8} 9 return NULL; 10} 11 void push (Object item) {12 node T = new node (item); 13 T. next = top; 14 top = T; 15} 16}

Implementing a queue

Queue

1 class queue {2 node first, last; 3 void enqueue (Object item) {4 If (! First) {5 back = new node (item); 6 first = back; 7} else {8 back. next = new node (item); 9 back = back. next; 10} 11} 12 node dequeue (node N) {13 if (front! = NULL) {14 object item
= Front. Data; 15 front = front. Next; 16 return item; 17} 18 return NULL; 19} 20}


3 1 describe how you cocould use a single array to implement three stacks

3.1 how to use an array to implement three stacks
3.1 Answer:
Solution 1:
Divide the array into three equal parts, each of which is used independently to implement the stack.
* First stack: from 0 to N/3
* Second stack: from N/3 to 2N/3
* Third stack: From 2n/3 to n
This solution is based on no additional instructions for the use of each stack, So we divide a fixed size for each stack.

Solution 2:
In solution 2, there is space available in the main array, and the stack can grow.
Each time a space is allocated to the stack, a space address is recorded in the new space. In this way, each element in the stack has a pointer pointing to the previous element.
One problem with this implementation method is that if a stack pops up a space (releasing space), the space will not be used as the free space after the array. In this way, we cannot use the new free space.
To solve this problem, we use a list to record idle space. When a new free space appears, we add it to this table. If you need to allocate a new space, delete an element from the table.
This method enables the three stacks to dynamically use the array space, but this is in exchange for increasing the space complexity.

3 2 How wocould you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and Min shoshould all operate in O (1) Time

3.2 is suitable for implementing one stack, in addition to the push and pop functions, there are min functions and the minimum elements in the min function range stack. The time complexity of the push, pop, and Min functions is O (1 ).
3.2 answers:
the minimum value in the current stack is recorded in the nodes in each stack. When calling the min () function, you only need to check the minimum value recorded in the top element of the stack.
but the problem with this solution is that if the stack needs to record a large number of elements, this method will consume a lot of space. Because the minimum value is recorded in each stack element. Can this be improved?
we can create a secondary stack to record only the smallest elements.
this method is not more efficient. In stack S2, only the minimum value is recorded, which avoids the record of a large amount of redundant data.

3 3 Imagine a (literal) stack of plates if the Stack gets too high, it might topple there-fore, in real life, we wowould likely start a new stack when the previous stack exceeds some threshold implement a data structure setofstacks that mimics this
Setof-stacks shocould be composed of several stacks, and shocould create a new stack once the previous one exceeds capacity setofstacks push () and setofstacks POP () shocould behave identically to a single stack (that is, pop () shocould return the same values as it
Wocould if there were just a single stack) Follow up implement a function popat (INT index) which performs a pop operation on a specific sub-Stack

3.3 imagine: If a pile of dishes are piled up too high, it will easily fall down. So in reality, if the fruit plate is heap to a certain height, we will start a new heap. Now we have implemented a new data structure to simulate this phenomenon. Setofstack contains many stacks. When a stack reaches the upper limit, the next stack is enabled. Setofstack. Push and setofstack. Pop should be the same as normal Stack operations.
Advanced:
Implement a function popat (INT index) to specify the stack on which elements are popped up.
3.3 answer:
According to the question, our data structure should basically be such a framework:

Because it has the same effect as the normal Stack push (), that is to say, each push () operation must put the elements in the most recently used stack. However, when the stack is full, a new stack must be created and re-written. The implementation of push is as follows:

How can pop () be implemented? Similar to push (), it must also be operated on the latest stack. However, if the last stack is empty, it should be removed.

What about how to deal with advanced problems?
This issue is indeed a bit difficult. Implementation is also troublesome, because the entire system should look like a "flip" system. If an element pops up from Stack 1, we need to press the element at the bottom of stack 2 to the top of stack 1. The elements of stack 3 need to go to stack 2 ....
Note: You may disagree with me. We do not need to "flip" the entire stack to implement this function. Every stack in the system does not need to be full. This saves a lot of time complexity, especially when the stack is very large. However, if all the stacks except the last stack must be full, this method will not work. You can communicate with the interviewer and decide what structure to use.

3 4 in the classic problem of the towers of Hanoi, you have 3 rods and N disks of different sizes which can slide onto any tower the puzzle starts with disks sorted in ascending order of size from top to bottom (E g, each disk sits on top of
Even larger one) You have the following constraints: (a) only one disk can be moved at a time (B) A disk is slid off the top of one rod onto the next rod (c) a disk can only be placed on top of a larger disk write a program to move the disks from the first
Rod to the last using stacks

3.4 The Classic Tower of Hanoi has three columns with N plates of different sizes on the column. The starting state of the tower of Hanoi Problem is that all the dishes are worn on the pillar from small to large (the largest dish below ). The following three restrictions are met: (a) only one plate can be moved at a time; (B) only the plate at the top of each column can be moved; (c) any dish can only be placed on a dish larger than it. Write a paragraphProgram(Stack required), move all the dishes on the first column to the last column.

3.4 answer:
First, consider the algorithm for solving the problem: Move n dishes from the first column to the last column. Let's start with the simplest situation. If there is only one dish, move it directly to the final pillar. What about the two dishes?
(1) first move the first dish from the first pillar to the second
(2) Move the second dish from the first pillar to the third
(3) Move the plate on the second pillar to the third pillar!
What about the three dishes?
(1) move two dishes to the second pillar.
(2) Move the third dish to the third pillar
(3) Move the two plates on the second pillar to the third pillar by means of shipment.
It is obvious that recursion is used.AlgorithmYou can solve this question:

3.5 implement a myqueue class which implements a queue using two stacks

3.5 use two stacks to implement a queue
3.5 answer:
The biggest difference between a stack and a queue is: first, First, Second, first, and foremost. However, the requirements of the question make the action of PEEK and pop exactly the opposite. Then we can use the Second stack to reverse the order of the elements in the stack. (First, all the elements are added to stack S1, so that the elements of the most advanced Stack are located at the bottom of the stack and finally at the top of the stack. Then, the elements in S1 are popped up in sequence and pushed into Stack S2. In this way, the advanced elements in S2 are placed at the bottom of the stack .)
However, if the actions on the queue and the outbound queue are repeated, I will reverse them repeatedly in the S1 and S2 stacks. There are actually ways to be lazy.
When an element is to enter the queue, it is directly pressed as in stack S1. If the element needs to be columns out of the queue, check if S2 contains any element, if the element in S1 is not "Inverted" into S2 using the previous method, if the element in S2 is not null, It is the element in the queue. This method will not be reversed between two stacks:

3 6 write a program to sort a stack in ascending order you shocould not make any assumptions about how the stack is implemented the following are the only functions that shoshould be used to write this program: push | pop | peek | isempty

3.6 write a program to sort the stack in ascending order. This stack is a common stack and cannot have other assumptions. Function implementation can only call the push (), pop (), peek (), and isempty functions.
3.6 answer:
Create another stack, an element pops up from the original stack to the new stack. Then compare the elements at the top of the original stack and the size at the top of the new stack. If the sorting rules are met, enter the new stack again. If not, the elements in the new stack are compared one by one until the sorting relationship is satisfied. This is similar to the insert sorting method. The complexity is O (n ^ 2 ).

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.