栈和队列的面试题Java实现,Stack类继承于Vector这两个类都不推荐使用

 

在 thinking in java中看到过说Stack类继承于Vector,而这两个类都不推荐使用了,但是在做一到OJ题时,我用LinkedList来模拟栈和直接用Stack,发现在进行入栈出栈操作时Stack的速度竟然还快一点

然而需要多线程的时候有Collections.synchronizedList,还有java.util.concurrent包下的。所以还是忘了这货吧。

Java 中还有非常多的地方使用到了栈。

栈是一种数据结构,所以它使用的非常普遍。面试中遇到它的可能性也比较大,所以还是很有必要掌握的。

java.util.Stack 类 Java 官方已经不在建议使用了。现在官方推荐使用 java.util.Deque。类似下面的用法:

Deque<Integer> stack = new ArrayDeque<Integer>();

那么 Java 为什么不推荐使用 Stack 呢?为什么 Stack 被废弃了呢?

很简单,因为 Stack 是 JDK 1.0 的产物。它继承自 Vector,Vector 都不被推荐使用了,你说 Stack 还会被推荐吗?

当初 JDK1.0 在开发时,可能为了快速的推出一些基本的数据结构操作,所以推出了一些比较粗糙的类。比如,Vector、Stack、Hashtable等。这些类中的一些方法加上了 synchronized 关键字,容易给一些初级程序员在使用上造成一些误解!而且在之前的几个版本中,性能还不怎么好。

基于 Vector 实现的栈 Stack。底层实际上还是数组,所以还是存在需要扩容。Vector 是由数组实现的集合类,他包含了大量集合处理的方法。而 Stack 之所以继承 Vector,是为了复用 Vector 中的方法,来实现进栈(push)、出栈(pop)等操作。这里就是 Stack 设计不好的地方,既然只是为了实现栈,不用链表来单独实现,而是为了复用简单的方法而迫使它继承 Vector,Stack 和 Vector 本来是毫无关系的。这使得 Stack 在基于数组实现上效率受影响,另外因为继承 Vector 类,Stack 可以复用 Vector 大量方法,这使得 Stack 在设计上不严谨。

基于上一篇文章中,我们对栈存在的一个基本认识,下面我们使用 LinkedList 自己实现一个栈。

package com.xttblog;
import java.util.LinkedList;
public class Stack<E> {
	LinkedList<E> list;
	public Stack(){
        list = new LinkedList();
    }
    public E pop(){
        return list.removeLast();
    }
    public void push(E o){
        list.add(o);
    }
    public E getTop(){
        return list.getLast();
    }
    public boolean isEmpty(){
        return list.size()==0;
    }
    public int size(){
        return list.size();
    }
}

Java 中的 Stack

栈的最基本的特征是LIFO(Last In First Out),因此栈又被称为后进先出的线性表。所以上面采用 LinkedList 实现的栈看起来也非常的简单。虽然简单,但我们并不需要重复的轮子。Java 提供了 Deuqe。Deque 是继承自 Queue,而 Stack 是继承自 Vector。Java 中的 Deuqe,即“double ended queue”的缩写,是 Java 中的双端队列集合类型。Deque 具备普通队列 FIFO 的功能,同时它也具备了 Stack 的 LIFO 功能,并且保留了 push 和 pop 函数,所以使用起来应该是一点障碍都没有。

ArrayDeque 是 Deque 接口的一种具体实现,是依赖于可变数组来实现的。ArrayDeque 没有容量限制,可根据需求自动进行扩容。ArrayDeque 可以作为栈来使用,效率要高于 Stack。ArrayDeque 也可以作为队列来使用,效率相较于基于双向链表的 LinkedList 也要更好一些。注意,ArrayDeque 不支持为  null 的元素。

 

 

 

栈和队列的面试题Java实现

二、栈和队列:

面试的时候,栈和队列经常会成对出现来考察。本文包含栈和队列的如下考试内容:

  (1)栈的创建

  (2)队列的创建

  (3)两个栈实现一个队列

  (4)两个队列实现一个栈

  (5)设计含最小函数min()的栈,要求min、push、pop、的时间复杂度都是O(1)

  (6)判断栈的push和pop序列是否一致

1、栈的创建:

    我们接下来通过链表的形式来创建栈,方便扩充。

代码实现:

复制代码
 1 public class Stack {
 2 
 3     public Node head;
 4     public Node current;
 5 
 6 
 7     //方法:入栈操作
 8     public void push(int data) {
 9         if (head == null) {
10             head = new Node(data);
11             current = head;
12         } else {
13             Node node = new Node(data);
14             node.pre = current;//current结点将作为当前结点的前驱结点
15             current = node;  //让current结点永远指向新添加的那个结点
16         }
17     }
18 
19     public Node pop() {
20         if (current == null) {
21             return null;
22         }
23 
24         Node node = current; // current结点是我们要出栈的结点
25         current = current.pre;  //每出栈一个结点后,current后退一位
26         return node;
27 
28     }
29 
30 
31     class Node {
32         int data;
33         Node pre;  //我们需要知道当前结点的前一个结点
34 
35         public Node(int data) {
36             this.data = data;
37         }
38     }
39 
40 
41     public static void main(String[] args) {
42 
43         Stack stack = new Stack();
44         stack.push(1);
45         stack.push(2);
46         stack.push(3);
47 
48         System.out.println(stack.pop().data);
49         System.out.println(stack.pop().data);
50         System.out.println(stack.pop().data);
51     }
52 
53 }
复制代码

入栈操作时,14、15行代码是关键。

运行效果:

e6e0ae76-0eed-4f1c-95a0-10e543237d63

2、队列的创建:

  队列的创建有两种形式:基于数组结构实现(顺序队列)、基于链表结构实现(链式队列)。

  我们接下来通过链表的形式来创建队列,这样的话,队列在扩充时会比较方便。队列在出队时,从头结点head开始。

代码实现:

    入栈时,和在普通的链表中添加结点的操作是一样的;出队时,出的永远都是head结点。

复制代码
 1 public class Queue {
 2     public Node head;
 3     public Node curent;
 4 
 5     //方法:链表中添加结点
 6     public void add(int data) {
 7         if (head == null) {
 8             head = new Node(data);
 9             curent = head;
10         } else {
11             curent.next = new Node(data);
12             curent = curent.next;
13         }
14     }
15 
16     //方法:出队操作
17     public int pop() throws Exception {
18         if (head == null) {
19             throw new Exception("队列为空");
20         }
21 
22         Node node = head;  //node结点就是我们要出队的结点
23         head = head.next; //出队之后,head指针向下移
24 
25         return node.data;
26 
27     }
28 
29 
30     class Node {
31         int data;
32         Node next;
33 
34         public Node(int data) {
35             this.data = data;
36         }
37     }
38 
39 
40     public static void main(String[] args) throws Exception {
41         Queue queue = new Queue();
42         //入队操作
43         for (int i = 0; i < 5; i++) {
44             queue.add(i);
45         }
46 
47         //出队操作
48         System.out.println(queue.pop());
49         System.out.println(queue.pop());
50         System.out.println(queue.pop());
51 
52     }
53 }
复制代码

运行效果:

fd770486-0cbe-45d8-96a7-0f3116045a35

3、两个栈实现一个队列:

思路:

    栈1用于存储元素,栈2用于弹出元素,负负得正

    说的通俗一点,现在把数据1、2、3分别入栈一,然后从栈一中出来(3、2、1),放到栈二中,那么,从栈二中出来的数据(1、2、3)就符合队列的规律了,即负负得正。

完整版代码实现:

复制代码
 1 import java.util.Stack;
 2 
 3 /**
 4  * Created by smyhvae on 2015/9/9.
 5  */
 6 public class Queue {
 7 
 8     private Stack<Integer> stack1 = new Stack<>();//执行入队操作的栈
 9     private Stack<Integer> stack2 = new Stack<>();//执行出队操作的栈
10 
11 
12     //方法:给队列增加一个入队的操作
13     public void push(int data) {
14         stack1.push(data);
15 
16     }
17 
18     //方法:给队列正价一个出队的操作
19     public int pop() throws Exception {
20 
21 
22         if (stack2.empty()) {//stack1中的数据放到stack2之前,先要保证stack2里面是空的(要么一开始就是空的,要么是stack2中的数据出完了),不然出队的顺序会乱的,这一点很容易忘
23 
24             while (!stack1.empty()) {
25                 stack2.push(stack1.pop());//把stack1中的数据出栈,放到stack2中【核心代码】
26             }
27 
28         }
29 
30         if (stack2.empty()) { //stack2为空时,有两种可能:1、一开始,两个栈的数据都是空的;2、stack2中的数据出完了
31             throw new Exception("队列为空");
32         }
33 
34         return stack2.pop();
35     }
36 
37     public static void main(String[] args) throws Exception {
38         Queue queue = new Queue();
39         queue.push(1);
40         queue.push(2);
41         queue.push(3);
42 
43         System.out.println(queue.pop());
44 
45         queue.push(4);
46 
47         System.out.println(queue.pop());
48         System.out.println(queue.pop());
49         System.out.println(queue.pop());
50 
51     }
52 
53 }
复制代码

注意第22行和第30行代码的顺序,以及注释,需要仔细理解其含义。

运行效果:

e5334faf-a36e-4aa2-9fe3-18157717bacd

4、两个队列实现一个栈:

思路:

  将1、2、3依次入队列一, 然后最上面的3留在队列一,将下面的2、3入队列二,将3出队列一,此时队列一空了,然后把队列二中的所有数据入队列一;将最上面的2留在队列一,将下面的3入队列二。。。依次循环。

代码实现:

复制代码
 1 import java.util.ArrayDeque;
 2 import java.util.Queue;
 3 
 4 /**
 5  * Created by smyhvae on 2015/9/9.
 6  */
 7 public class Stack {
 8 
 9     Queue<Integer> queue1 = new ArrayDeque<Integer>();
10     Queue<Integer> queue2 = new ArrayDeque<Integer>();
11 
12     //方法:入栈操作
13     public void push(int data) {
14         queue1.add(data);
15     }
16 
17     //方法:出栈操作
18     public int pop() throws Exception {
19         int data;
20         if (queue1.size() == 0) {
21             throw new Exception("栈为空");
22         }
23 
24         while (queue1.size() != 0) {
25             if (queue1.size() == 1) {
26                 data = queue1.poll();
27                 while (queue2.size() != 0) {  //把queue2中的全部数据放到队列一中
28                     queue1.add(queue2.poll());
29                     return data;
30                 }
31             }
32             queue2.add(queue1.poll());
33         }
34         throw new Exception("栈为空");//不知道这一行的代码是什么意思
35     }
36 
37     public static void main(String[] args) throws Exception {
38         Stack stack = new Stack();
39 
40         stack.push(1);
41         stack.push(2);
42         stack.push(3);
43 
44         System.out.println(stack.pop());
45         System.out.println(stack.pop());
46         stack.push(4);
47     }
48 }
复制代码

运行效果:

7c0470f9-0558-4b00-9e04-51d018dd6081

5、设计含最小函数min()的栈,要求min、push、pop、的时间复杂度都是O(1)。min方法的作用是:就能返回是栈中的最小值。【微信面试题】

普通思路:

  一般情况下,我们可能会这么想:利用min变量,每次添加元素时,都和min元素作比较,这样的话,就能保证min存放的是最小值。但是这样的话,会存在一个问题:如果最小的元素出栈了,那怎么知道剩下的元素中哪个是最小的元素呢?

改进思路:

    这里需要加一个辅助栈,用空间换取时间。辅助栈中,栈顶永远保存着当前栈中最小的数值。具体是这样的:原栈中,每次添加一个新元素时,就和辅助栈的栈顶元素相比较,如果新元素小,就把新元素的值放到辅助栈中,如果新元素大,就把辅助栈的栈顶元素再copy一遍放到辅助栈的栈顶;原栈中,出栈时,

完整代码实现:

复制代码
 1 import java.util.Stack;
 2 
 3 /**
 4  * Created by smyhvae on 2015/9/9.
 5  */
 6 public class MinStack {
 7 
 8     private Stack<Integer> stack = new Stack<Integer>();
 9     private Stack<Integer> minStack = new Stack<Integer>(); //辅助栈:栈顶永远保存stack中当前的最小的元素
10 
11 
12     public void push(int data) {
13         stack.push(data);  //直接往栈中添加数据
14 
15         //在辅助栈中需要做判断
16         if (minStack.size() == 0 || data < minStack.peek()) {
17             minStack.push(data);
18         } else {
19             minStack.add(minStack.peek());   //【核心代码】peek方法返回的是栈顶的元素
20         }
21     }
22 
23     public int pop() throws Exception {
24         if (stack.size() == 0) {
25             throw new Exception("栈中为空");
26         }
27 
28         int data = stack.pop();
29         minStack.pop();  //核心代码
30         return data;
31     }
32 
33     public int min() throws Exception {
34         if (minStack.size() == 0) {
35             throw new Exception("栈中空了");
36         }
37         return minStack.peek();
38     }
39 
40     public static void main(String[] args) throws Exception {
41         MinStack stack = new MinStack();
42         stack.push(4);
43         stack.push(3);
44         stack.push(5);
45 
46         System.out.println(stack.min());
47     }
48 }
复制代码

604a9d9a-6e44-4cdf-ab4a-da3070e39ea1

6、判断栈的push和pop序列是否一致:

    通俗一点讲:已知一组数据1、2、3、4、5依次进栈,那么它的出栈方式有很多种,请判断一下给出的出栈方式是否是正确的?

例如:

数据:

  1、2、3、4、5

出栈1:

  5、4、3、2、1(正确)

出栈2:

  4、5、3、2、1(正确)

出栈3:

  4、3、5、1、2(错误)

完整版代码:

复制代码
 1 import java.util.Stack;
 2 
 3 /**
 4  * Created by smyhvae on 2015/9/9.
 5  */
 6 public class StackTest {
 7 
 8 
 9     //方法:data1数组的顺序表示入栈的顺序。现在判断data2的这种出栈顺序是否正确
10     public static boolean sequenseIsPop(int[] data1, int[] data2) {
11         Stack<Integer> stack = new Stack<Integer>(); //这里需要用到辅助栈
12 
13         for (int i = 0, j = 0; i < data1.length; i++) {
14             stack.push(data1[i]);
15 
16             while (stack.size() > 0 && stack.peek() == data2[j]) {
17                 stack.pop();
18                 j++;
19             }
20         }
21         return stack.size() == 0;
22     }
23 
24 
25     public static void main(String[] args) {
26 
27         Stack<Integer> stack = new Stack<Integer>();
28 
29         int[] data1 = {1, 2, 3, 4, 5};
30         int[] data2 = {4, 5, 3, 2, 1};
31         int[] data3 = {4, 5, 2, 3, 1};
32 
33         System.out.println(sequenseIsPop(data1, data2));
34         System.out.println(sequenseIsPop(data1, data3));
35     }
36 }
复制代码

代码比较简洁,但也比较难理解,要仔细体会。

运行效果:

1cca8bbf-0eee-4049-88b6-d10a4f8c838a

原文地址:https://www.cnblogs.com/timssd/p/4796138.html