Java interview questions: Implementation of stacks and queues

Source: Internet
Author: User

Java interview questions: Implementation of stacks and queues

During the interview, stacks and queues are often checked in pairs. This article includes the following stack and queue test content:

1) stack Creation

2) create a queue

3) Two stacks implement one queue

4) two queues implement one stack

5) design the stack containing the min () function. The time complexity required for min, push, pop, and so on is O (1)

6) Determine whether the push and pop sequences of the stack Are consistent

1. Stack creation:

Next we will create a stack in the form of a linked list to facilitate expansion.

Code implementation:

Public class Stack {

Public Node head;
Public Node current;

// Method: stack-based operation
Public void push (int data ){
If (head = null ){
Head = new Node (data );
Current = head;
} Else {
Node node = new Node (data );
Node. pre = current; // current node serves as the front node of the current node
Current = node; // Let the current node always point to the newly added node
}
}

Public Node pop (){
If (current = null ){
Return null;
}

Node node = current; // the current Node is the node that we want to output the stack.
Current = current. pre; // after one node on each outbound stack, the current node returns one
Return node;

}

Class Node {
Int data;
Node pre; // we need to know the previous Node of the current Node

Public Node (int data ){
This. data = data;
}
}

Public static void main (String [] args ){

Stack stack = new Stack ();
Stack. push (1 );
Stack. push (2 );
Stack. push (3 );

System. out. println (stack. pop (). data );
System. out. println (stack. pop (). data );
System. out. println (stack. pop (). data );
}

}

During stack operations, lines 14 and 15 are critical.

Running effect:

2. Create a queue:

Queues can be created in two forms: sequential queues Based on the array structure) and chain queues Based on the linked list structure ).

We will create a queue in the form of a linked list. In this way, the queue will be more convenient during expansion. When the queue is out of the queue, it starts from the first node head.

Code implementation:

The operations for adding nodes to the stack are the same as those for adding nodes to a common linked list. When a node is out of the queue, it is always a head node.

Public class Queue {
Public Node head;
Public Node curent;

// Method: add nodes to the linked list
Public void add (int data ){
If (head = null ){
Head = new Node (data );
Curent = head;
} Else {
Curent. next = new Node (data );
Curent = curent. next;
}
}

// Method: Team-out operation
Public int pop () throws Exception {
If (head = null ){
Throw new Exception ("the queue is empty ");
}

Node node = head; // The node is the Node we want to team up.
Head = head. next; // after leaving, the head pointer moves down

Return node. data;

}

Class Node {
Int data;
Node next;

Public Node (int data ){
This. data = data;
}
}

Public static void main (String [] args) throws Exception {
Queue queue = new Queue ();
// Queue operations
For (int I = 0; I <5; I ++ ){
Queue. add (I );
}

// Team-out operations
System. out. println (queue. pop ());
System. out. println (queue. pop ());
System. out. println (queue. pop ());

}
}

Running effect:

3. Two stacks implement one queue:

Ideas:

Stack 1 is used to store elements, stack 2 is used to pop up elements, negative Positive.

To put it bluntly, we now add data 1, 2, and 3 to stack 1 respectively, and then 3, 2, and 1 from Stack 1 to stack 2, data 1, 2, and 3 from the Second stack must comply with the rules of the queue, that is, the negative is positive.

Full Version code implementation:

Import java. util. Stack;

/**
* Created by smyhvae on 2015/9/9.
*/
Public class Queue {

Private Stack <Integer> stack1 = new Stack <> (); // The Stack for which the queue operation is performed.
Private Stack <Integer> stack2 = new Stack <> (); // Stack that executes the team-out operation

// Method: add an operation to the queue
Public void push (int data ){
Stack1.push (data );

}

// Method: A forward operation for the queue at a regular price
Public int pop () throws Exception {

If (stack2.empty () {// before putting the data in stack1 to stack2, make sure that the data in stack2 is empty at the beginning, or that the data in stack2 is finished ), otherwise, the order of departure will be messy, which is easy to forget.

While (! Stack1.empty ()){
Stack2.push (stack1.pop (); // extract the data in stack1 from the stack and place it in the core code of stack2]
}

}

If (stack2.empty () {// when stack2 is null, there are two possibilities: 1. At the beginning, the data on both stacks is empty; 2. The data in stack2 is out.
Throw new Exception ("the queue is empty ");
}

Return stack2.pop ();
}

Public static void main (String [] args) throws Exception {
Queue queue = new Queue ();
Queue. push (1 );
Queue. push (2 );
Queue. push (3 );

System. out. println (queue. pop ());

Queue. push (4 );

System. out. println (queue. pop ());
System. out. println (queue. pop ());
System. out. println (queue. pop ());

}

}

Pay attention to the order of 22nd and 30th lines of code, as well as comments, which need to be carefully understood.

Running effect:

4. Two queues implement one stack:

Ideas:

Add 1, 2, and 3 to queue 1 in sequence, and then leave the top 3 to queue 1. Then, put 2 and 3 to queue 2 and 3 to queue 1. At this time, the queue is empty, then, all the data in the second queue is put into the first queue; the top two are left in the first queue, and the following three are put into the second queue... In turn.

Code implementation:

Import java. util. ArrayDeque;
Import java. util. Queue;

/**
* Created by smyhvae on 2015/9/9.
*/
Public class Stack {

Queue <Integer> queue1 = new ArrayDeque <Integer> ();
Queue <Integer> queue2 = new ArrayDeque <Integer> ();

// Method: stack-based operation
Public void push (int data ){
Queue1.add (data );
}

// Method: Out-of-stack operations
Public int pop () throws Exception {
Int data;
If (queue1.size () = 0 ){
Throw new Exception ("Stack is empty ");
}

While (queue1.size ()! = 0 ){
If (queue1.size () = 1 ){
Data = queue1.poll ();
While (queue2.size ()! = 0) {// put all data in queue2 to queue 1
Queue1.add (queue2.poll ());
Return data;
}
}
Queue2.add (queue1.poll ());
}
Throw new Exception ("Stack is empty"); // I don't know what the code in this line means
}

Public static void main (String [] args) throws Exception {
Stack stack = new Stack ();

Stack. push (1 );
Stack. push (2 );
Stack. push (3 );

System. out. println (stack. pop ());
System. out. println (stack. pop ());
Stack. push (4 );
}
}

Running effect:

5. Design a stack containing the min () function. The time complexity required for min, push, pop, and so on is O (1). The min method returns the minimum value in the stack. Interview Questions]

General idea:

In general, we may think this way: using the min variable, every time an element is added, it is compared with the min element. In this way, the min value can be kept as the minimum value. But in this case, there will be a problem: If the smallest element is out of the stack, how can we know which one of the remaining elements is the smallest element?

Improvement ideas:

Add an auxiliary stack here,Exchange Space for time. In the secondary stack, the top of the stack always stores the smallest value in the current stack. Specifically:In the original stack, each time a new element is added, it is compared with the top element of the stack of the secondary stack. If the new element is small, the value of the new element is placed in the secondary stack. If the new element is large, copy the top element of the secondary stack to the top of the secondary stack;In the original stack, when the stack is exited,

Complete code implementation:

Import java. util. Stack;

/**
* Created by smyhvae on 2015/9/9.
*/
Public class MinStack {

Private Stack <Integer> stack = new Stack <Integer> ();
Private Stack <Integer> minStack = new Stack <Integer> (); // secondary stack: the top of the Stack always saves the current smallest element in the Stack.

Public void push (int data ){
Stack. push (data); // Add data directly to the stack

// Judgment is required in the auxiliary Stack
If (minStack. size () = 0 | data <minStack. peek ()){
MinStack. push (data );
} Else {
MinStack. add (minStack. peek (); // core code] the peek method returns the elements at the top of the stack.
}
}

Public int pop () throws Exception {
If (stack. size () = 0 ){
Throw new Exception ("empty in stack ");
}

Int data = stack. pop ();
MinStack. pop (); // core code
Return data;
}

Public int min () throws Exception {
If (minStack. size () = 0 ){
Throw new Exception ("Empty stack ");
}
Return minStack. peek ();
}

Public static void main (String [] args) throws Exception {
MinStack stack = new MinStack ();
Stack. push (4 );
Stack. push (3 );
Stack. push (5 );

System. out. println (stack. min ());
}
}

6. Determine whether the push and pop sequences of the stack Are consistent:

To put it simply, we know that a group of data 1, 2, 3, 4, and 5 are pushed to the stack in sequence, so there are many ways to exit the stack, check whether the stack exit method is correct?

For example:

Data:

1, 2, 3, 4, 5

Outbound stack 1:

5, 4, 3, 2, and 1 are correct)

Outbound stack 2:

4, 5, 3, 2, and 1)

Outbound stack 3:

4, 3, 5, 1, and 2 errors)

Full Version code:

Import java. util. Stack;

/**
* Created by smyhvae on 2015/9/9.
*/
Public class StackTest {

// Method: the order of the data1 array indicates the order of inbound stack. Check whether the order of the output stack of data2 is correct.
Public static boolean sequenseIsPop (int [] data1, int [] data2 ){
Stack <Integer> stack = new Stack <Integer> (); // The secondary Stack is used here.

For (int I = 0, j = 0; I <data1.length; I ++ ){
Stack. push (data1 [I]);

While (stack. size ()> 0 & stack. peek () = data2 [j]) {
Stack. pop ();
J ++;
}
}
Return stack. size () = 0;
}

Public static void main (String [] args ){

Stack <Integer> stack = new Stack <Integer> ();

Int [] data1 = {1, 2, 3, 4, 5 };
Int [] data2 = {4, 5, 3, 2, 1 };
Int [] data3 = {4, 5, 2, 3, 1 };

System. out. println (sequenseIsPop (data1, data2 ));
System. out. println (sequenseIsPop (data1, data3 ));
}
}

The code is concise, but difficult to understand.

Running effect:

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.