美文网首页
两个堆栈实现队列及排序

两个堆栈实现队列及排序

作者: 游侠_6fb7 | 来源:发表于2019-02-26 08:52 被阅读0次

两个堆栈实现队列及排序


package com.ranger.demo;

import java.util.Stack;

/**

* Created by on 2019/2/11.

*/

public class TestStack {

Stackstack1 =new Stack();

    Stackstack2 =new Stack();

    /**

* 初始化,插入

    * @param num

    */

    private void push(int num) {

stack1.push(num);

    }

/**

* 实现队列

    * @return

    */

    private int pop() {

Integerp =null;

        if (!stack2.isEmpty()) {

p =stack2.pop();

        }else {

while (!stack1.isEmpty()) {

p =stack1.pop();

                stack2.push(p);

            }

if (!stack2.empty()) {

p =stack2.pop();

            }

}

return p;

    }

/**

* 实现排序

    * @param stack

    * @return

    */

    private Stacksort(Stack stack) {

Stack tempStack =new Stack<>();

        while (!stack.isEmpty()) {

int cur = stack.pop();

            while (!tempStack.isEmpty() && tempStack.peek() < cur) {

stack.push(tempStack.pop());

            }

tempStack.push(cur);

        }

return tempStack;

    }

public static void main(String args[]) {

TestStack testStack =new TestStack();

        int a[] = {2, 5, 6, 1, 10};

        System.out.println("----入栈----");

        for (int b : a) {

testStack.push(b);

            System.out.print(b +"\t");

        }

System.out.println("\n----队列先进先出----");

        int s = a.length;

        for (int i =0; i < s; i++) {

System.out.print(testStack.pop() +"\t");

        }

for (int b : a) {

testStack.push(b);

        }

System.out.println("\n----排序----");

        Stack sort = testStack.sort(testStack.stack1);

        while (!sort.isEmpty()) {

System.out.print(sort.pop() +"\t");

        }

}

}

相关文章

  • 两个堆栈实现队列及排序

    两个堆栈实现队列及排序

  • 在Python中实现两个堆栈的队列

    在Python中实现两个堆栈的队列。数据结构了解堆栈和队列。然后用两个堆栈实现一个队列。堆栈和队列都是列表。但它们...

  • 【面试题】算法

    一、简单算法的实现 1.用两个堆栈实现队列 class Quene{ constructor(){ thi...

  • 3-15 算法类

    排序 队列 链表堆栈 是一定要准备的,JS的数组本身就具备堆栈和队列的特性.pop push shift unsh...

  • 数据结构

    知识点:堆栈,队列,排序算法 堆栈: 一.基本概念: 栈顶,栈底,出栈(pop),入栈(push),空栈 1.堆栈...

  • 数组

    原文JS中的数组提供了四个操作,以便让我们实现队列与堆栈!小理论:队列:先进先出堆栈:后进先出实现队列的方法:sh...

  • 机试常用算法和题型-栈和队列专题

    堆栈+ordermap使用括号匹配 堆栈使用简单计算器 栈+队列实现中缀转后缀,计算后缀表达式 栈+队列计算,包括...

  • 队列、堆栈和优先队列介绍及Redis实现

    前言 队列、堆栈和优先队列是编程中常见的数据结构。本文首先简单介绍一下这几种数据结构,然后介绍如何用Redis实现...

  • 使用两个队列模拟堆栈结构

    两个队列模拟一个堆栈,队列是先进先出,而堆栈是先进后出。模拟如下队列a和b(1)入栈:a队列为空,b为空。例:则将...

  • Java LinkedList

    基本概念 LinkedList可以被当作堆栈、队列或双端队列进行操作。LinkedList 实现 List 接口,...

网友评论

      本文标题:两个堆栈实现队列及排序

      本文链接:https://www.haomeiwen.com/subject/tdpoyqtx.html