java——棧和隊列 面試題

(1)棧的建立java

(2)隊列的建立node

(3)兩個棧實現一個隊列數組

(4)兩個隊列實現一個棧ide

(5)設計含最小函數min()的棧,要求min、push、pop、的時間複雜度都是O(1)函數

(6)判斷棧的push和pop序列是否一致this

 

-------------------------------------------------------------------------------------------------spa

1. 棧的建立設計

public class Stack{
    public Node head;
    public Node current;

    //入棧
    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;  ////讓current結點永遠指向新添加的那個結點
        }
    }

    public Node pop(){
        if(current==null){
            return null;    
        } 
        Node node=current;
        current=current.pre; //current結點是咱們要出棧的結點
        return node;
    }

    class Node{
        int data;
        Node pre;
        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);
    }
}
View Code

 

2. 隊列的建立code

隊列的建立有兩種形式:基於數組結構實現(順序隊列)、基於鏈表結構實現(鏈式隊列)。blog

咱們接下來經過鏈表的形式來建立隊列,這樣的話,隊列在擴充時會比較方便。隊列在出隊時,從頭結點head開始。

入棧時,和在普通的鏈表中添加結點的操做是同樣的;出隊時,出的永遠都是head結點。

public class Queue{
    public Node head;
    public Node current;
    
    //鏈表中添加節點
    public void add(int data){
        if(head==null){
            head=new Node(data);
            current=head;
        }else{
            current.next=new Node(data);
            current=current.next;
        }
    }

    //出隊操做
    public int pop() throws Exception{
        if(head==null){
            throw new Exception("隊列爲空");
        }
        Node node=head;
        head=node.next;
        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();

        for(int i=0; i<5; i++){
            queue.add(i);
        }

        System.out.println(queue.pop());
        System.out.println(queue.pop());
        System.out.println(queue.pop());
    }
}
View Code

 

3. 兩個棧實現一個隊列

棧1用於存儲元素,棧2用於彈出元素,負負得正。

說的通俗一點,如今把數據一、二、3分別入棧一,而後從棧一中出來(三、二、1),放到棧二中,那麼,從棧二中出來的數據(一、二、3)就符合隊列的規律了,即負負得正。

 

import java.util.Stack;
 
/**
* Created by smyhvae on 2015/9/9.
*/
public class Queue {
 
private Stack<Integer> stack1 = new Stack<>();//執行入隊操做的棧
 private Stack<Integer> stack2 = new Stack<>();//執行出隊操做的棧
 
//方法:給隊列增長一個入隊的操做
 public void push(int data) {
  stack1.push(data);
 
}
 
//方法:給隊列正價一個出隊的操做
 public int pop() throws Exception {
 
if (stack2.empty()) {//stack1中的數據放到stack2以前,先要保證stack2裏面是空的(要麼一開始就是空的,要麼是stack2中的數據出完了),否則出隊的順序會亂的,這一點很容易忘
 
while (!stack1.empty()) {
    stack2.push(stack1.pop());//把stack1中的數據出棧,放到stack2中【核心代碼】
   }
 
}
 
if (stack2.empty()) { //stack2爲空時,有兩種可能:一、一開始,兩個棧的數據都是空的;二、stack2中的數據出完了
   throw new Exception("隊列爲空");
  }
 
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());
 
}
 
}
View Code

 

 

4. 兩個隊列實現一個棧

解法:

  1. 有兩個隊列q1和q2,先往q1內插入a,b,c,這作的都是棧的push操做。
  2. 如今要作pop操做,即要獲得c,這時能夠將q1中的a,b兩個元素所有dequeue並存入q2中,這時q2中元素爲a,b,對q1再作一次dequeue操做便可獲得c。
  3. 若是繼續作push操做,好比插入d,f,則把d,f插入到q2中,
  4. 此時若要作pop操做,則作步驟2
  5. 以此類推,就實現了用兩個隊列來實現一個棧的目的。

注意在此過程當中,新push進來的元素老是插入到非空隊列中,空隊列則用來保存pop操做以後的那些元素,那麼此時空隊列不爲空了,原來的非空隊列變爲空了,老是這樣循環。

對於push和pop操做,其時間爲O(n).

 

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>();
 
//方法:入棧操做
 public void push(int data) {
  queue1.add(data);
 }
 
//方法:出棧操做
 public int pop() throws Exception {
  int data;
  if (queue1.size() == 0) {
   throw new Exception("棧爲空");
  }
 
while (queue1.size() != 0) {
   if (queue1.size() == 1) {
    data = queue1.poll();
    while (queue2.size() != 0) { //把queue2中的所有數據放到隊列一中
     queue1.add(queue2.poll());
     return data;
    }
   }
   queue2.add(queue1.poll());
  }
  throw new Exception("棧爲空");//不知道這一行的代碼是什麼意思
 }
 
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);
 }
}
View Code

 

 

5. 設計含最小函數min()的棧,要求min、push、pop、的時間複雜度都是O(1)。min方法的做用是:就能返回是棧中的最小值

普通思路:

通常狀況下,咱們可能會這麼想:利用min變量,每次添加元素時,都和min元素做比較,這樣的話,就能保證min存放的是最小值。可是這樣的話,會存在一個問題:若是最小的元素出棧了,那怎麼知道剩下的元素中哪一個是最小的元素呢?

改進思路:

這裏須要加一個輔助棧,用空間換取時間。輔助棧中,棧頂永遠保存着當前棧中最小的數值。具體是這樣的:原棧中,每次添加一個新元素時,就和輔助棧的棧頂元素相比較,若是新元素小,就把新元素的值放到輔助棧中,若是新元素大,就把輔助棧的棧頂元素再copy一遍放到輔助棧的棧頂;原棧中,出棧時

import java.util.Stack;
public class MinStack {
 
private Stack<Integer> stack = new Stack<Integer>();
 private Stack<Integer> minStack = new Stack<Integer>(); //輔助棧:棧頂永遠保存stack中當前的最小的元素
 
public void push(int data) {
  stack.push(data); //直接往棧中添加數據
 
//在輔助棧中須要作判斷
  if (minStack.size() == 0 || data < minStack.peek()) {
   minStack.push(data);
  } else {
   minStack.add(minStack.peek()); //【核心代碼】peek方法返回的是棧頂的元素
  }
 }
 
public int pop() throws Exception {
  if (stack.size() == 0) {
   throw new Exception("棧中爲空");
  }
 
int data = stack.pop();
  minStack.pop(); //核心代碼
  return data;
 }
 
public int min() throws Exception {
  if (minStack.size() == 0) {
   throw new Exception("棧中空了");
  }
  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());
 }
}
 
View Code

 

 

6. 判斷棧的push和pop序列是否一致

通俗一點講:已知一組數據一、二、三、四、5依次進棧,那麼它的出棧方式有不少種,請判斷一下給出的出棧方式是不是正確的?

例如:

數據:

一、二、三、四、5

出棧1:

五、四、三、二、1(正確)

出棧2:

四、五、三、二、1(正確)

出棧3:

四、三、五、一、2(錯誤)

 

若是咱們但願pop的數字正好是棧頂數字,直接pop出棧便可;若是但願pop的數字目前不在棧頂,咱們就到push序列中尚未被push到棧裏的數字中去搜索這個數字,並把在它以前的全部數字都push進棧。若是全部的數字都被push進棧仍然沒有找到這個數字,代表該序列不多是一個pop序

import java.util.Stack;


public class StackTest {

    //方法:data1數組的順序表示入棧的順序。如今判斷data2的這種出棧順序是否正確
    public static boolean sequenseIsPop(int[] data1, int[] data2) {
        Stack<Integer> stack = new Stack<Integer>(); //這裏須要用到輔助棧

        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));
    }
}
相關文章
相關標籤/搜索