Java——队列/栈

1. PriorityQueue

优先队列是由PriorityQueue实现的。其中的类必须实现compareTo方法。
推荐博客https://www.cnblogs.com/Elliott-Su-Faith-change-our-life/p/7472265.html

方法:
1. 添加
	add(object);    //插入失败时抛出异常
 	offer(object);  //插入失败时返回false
2. 获取
	element()   //获取失败时抛出异常
	peek()      //获取失败时返回false
3. 删除
	remove()  //删除失败抛出异常
	poll()    //删除失败返回false

remove(object)
contain(object) 

Java优先队列默认是小根堆,对于类的优先队列,需要用接口Comparable重载其中的compareTo()函数,自行规定比较方法,可以故意与原比较大小相反,将小根堆变为大根堆。

/**
 *ProrityQueue
 *@author Hongchuan CAO
 */
package ACM;

import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
    public static void main(String arg[]){
        Node[] node = new Node[10];
        for(int i=0;i<10;i++){
            node[i] = new Node();
            node[i].a = 100-i;
        }
        Arrays.sort(node);
        for(Node xx : node){
            System.out.print(xx.a+" ");
        }
    }
}

class Node implements Comparable{
    public int a;
    @Override
    public int compareTo(Object obj){
        Node other = (Node) obj;
        if(this.a<other.a) return -1;
        else if(this.a>other.a) return 1;
        return 0;
    }
}

其中compareTo()默认比较方法,
在这里插入图片描述

Queue

Queue 是一个接口,其具体是由LinkedList实现实现的。
常用方法

Queue<String> queue = new LinkedList<String>();
//成功返回true,失败返回false或null

//添加到队尾
queue.offer(E x);
//获得并移除队首元素
queue.poll();
//获得队首元素但不删除
queue.peek();

// LinkedList
//添加
offerFirst(E e);
offerLast(E e);

//获取  (如果为空,返回NULL)
peekFirst();
peekLast();

//删除   (如果为空,返回NULL)
pollFirst();
pollLast();

Deque

Java 中没有双向队列的接口,可以直接使用LinkedList实现。

LinkedList<String> deque = new LinkedList<String>();

//加入元素
deque.addFirst();
deque.addLast();
deque.offerFirst();
deque.offerLast();

//获得元素
deque.getFisrt();
deque.getLast();
deque.peekFirst();
deque.peekLast();

//删除元素
deque.removeFirst();
deque.removeLast();
deque.pollFirst();
deque.pollLast();

Stack

Stack继承自Vector

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

//栈顶加入元素
stack.push(E x);
//栈顶获得元素
stack.peek();
//栈顶删除元素
stack.pop();

stack.empty();
stack.search(Object o);

也可以直接利用LinkedList实现栈的功能

LinkedList<String> stack = new LinkedList<String>();

stack.offerFirst();
stack.peekFirst();
stack.pollFirst();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值