Java implementation stack and queue face test _java

Source: Internet
Author: User

During the interview, stacks and queues often appear as pairs. This article contains the following test contents for stacks and queues:

(1) The creation of the stack

(2) Creation of queues

(3) Two stacks to implement a queue

(4) Two queues to implement a stack

(5) Design of the minimum function min () stack, requires min, push, pop, time complexity is O (1)

(6) To determine whether the stack of push and pop sequence is consistent

1, the creation of the stack:

We will then create the stack through the form of a linked list to facilitate expansion.

Code implementation:

public class Stack {public

Node head;
 public Node current;

Method: Stack 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 as the predecessor node of the current node
   = node;//Let the present 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 are going to stack current
  = current.pre///////////////////////

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);
 }

14, 15 lines of code are critical when the stack is in operation.

Operation Effect:

2, the creation of the queue:

Queues are created in two forms: based on Array structure implementation (sequential queues), based on the chain-list structure (chained queues).

We then create queues in the form of linked lists, so that queues are more convenient to expand. When the queue is out of the team, start with the head.

Code implementation:

When you enter the stack, it is the same as adding nodes to a common list; When you get out of the team, it's always the head node.

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

Method: Add node public
 void Add (int data) {
  if (head = = null) in the linked list {head
   = new node (data);
   curent = head;
  } else {
   Curent.next = new Node (data);
   curent = Curent.next;
  }

Method: Out team operation public
 int pop () throws Exception {
  if (head = = null) {
   throw new Exception ("Queue is empty");
  }

node node = head;//node node is the node head that we are going to be out of the team head
  = head.next;///After the team, the head pointer moves down the 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 action for
  (int i = 0; i < 5; i++) {
   queue.add (i);
  }

Out team Operation
  System.out.println (Queue.pop ());
  System.out.println (Queue.pop ());
  System.out.println (Queue.pop ());

}


Operation Effect:

3, two stacks to implement a queue:

Ideas:

Stack 1 is used to store elements, stack 2 is used for pop-up elements, negative negative positive.

To say the popular point, now put the data 1, 2, 3 into the stack of one, and then from the stack one out (3, 2, 1), put on the second stack, then, from the stack of data from the second (1, 2, 3) to meet the rules of the queue, that is negative negative 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 private STACK&LT;INTEGER&GT to perform the join operation ;

Stack2 = new stack<> ()//The Stack/method to perform a team operation: Add a queued operation to the queue public void push (int data) {Stack1.push (data); }//Method: Give the queue the right price one out of the operation public int pop () throws Exception {if (Stack2.empty ()) {//stack1 The data in the Stack2, make sure the Stack2 inside is empty (or a The beginning is empty, or the data in the Stack2 is out, otherwise the order of the team will be disorderly, it is easy to forget while (!stack1.empty ()) {Stack2.push (Stack1.pop ());//Put the data in the Stack1 out of the stack, Put in the Stack2 "core Code"} if (Stack2.empty ()) {//stack2 is empty, there are two possible: 1, at the beginning, two stacks of data are empty; 2, stack2 the data is over throw new Exception ("
  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 ());
 }

}

Note that the order of lines 22nd and 30th, along with the annotations, requires a careful understanding of their meaning.

Operation Effect:

4, two queues to implement a stack:

Ideas:

1, 2, 3 into the queue one, then the top 3 left in the queue one, the following 2, 3 into the queue two, 3 out of the queue one, at this time the queue is empty, and then put all the data in queue two into the queue one, the top 2 left in the queue one, the following 3 into the queue two ... Loop sequentially.

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: Into the stack operation public void push (int data) {queue1.add (data);
  }//Method: Out stack operation 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 the data in Queue2 into queue one queue1.add (Queue2.poll ());
    return data;
  } queue2.add (Queue1.poll ()); throw new Exception ("Stack is empty");/don't know what this line of code means} public static void Main (string[] args) throws Exception {stack Stac

K = new Stack ();
  Stack.push (1);
  Stack.push (2);

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

Operation Effect:

5, the design contains the minimum function min () the stack, requirements min, push, pop, the time complexity is O (1). The function of the Min method is to return the smallest value in the stack. "Micro-letter face test"

General ideas:

In general, we may think so: the use of the min variable, every time you add elements, and the min element for comparison, so that you can ensure that min holds the minimum value. But in this case, there is a problem: if the smallest element is out of the stack, how do you know which of the remaining elements is the smallest element?

Improvement Ideas:

Here you need to add a secondary stack, in exchange for time in space. In the secondary stack, the top of the stack always holds the smallest number in the current stack. The concrete is this: in the original stack, each time a new element is added, it is compared with the stack top element of the auxiliary 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, the stack top element of the auxiliary stack is again put on the stack top of the auxiliary stack; The original stack, the stack,

Full 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 stacks: The top of the stack always holds the smallest element public void push (int data) {Stack.push (data) currently in the stack;///////////////////////////////////// () = = 0 | |
  Data < Minstack.peek ()) {Minstack.push (data); else {Minstack.add (Minstack.peek ());////The "Core code" Peek method returns the element at the top of the Stack}} public int pop () throws Exception {if stack
  . Size () = = 0) {throw new Exception ("Empty stack");
  int data = Stack.pop (); Minstack.pop ();
 Core code return data;
  public int min () throws Exception {if (minstack.size () = = 0) {throw new Exception ("Stack Hollow");
 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 ()); }
}

Operation Effect:

6, to determine the stack of push and pop sequence is consistent:

Popular point: Known a group of data 1, 2, 3, 4, 5 in turn into the stack, then it's out of the stack way there are many kinds of, please judge the given out of the stack is the right way?

For example:

Data:

1, 2, 3, 4, 5

Out Stack 1:

5, 4, 3, 2, 1 (correct)

Out Stack 2:

4, 5, 3, 2, 1 (correct)

Out Stack 3:

4, 3, 5, 1, 2 (Error)

Full Version code:

Import Java.util.Stack; /** * Created by smyhvae on 2015/9/9.
*/
public class Stacktest {

Methods: The order of the data1 arrays represents the order of the stacks. Now to determine if the data2 order is correct
public static Boolean Sequenseispop (int[] data1, int[] data2) {
stack<integer> stack = new stack<integer> (); We need to use the secondary stack 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 relatively concise, but also more difficult to understand, to be carefully realized.

Operation Effect:

The above is the Java stack and queue of classic interview topics, I hope to help you pass the interview smoothly.

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.