基本思路: 首先用链表来实现栈,然后用map来保存<栈中元素个数,最大元素引用>元素
/**
* 实现一个栈,获取其中最大元素,获取时间复杂度为O(1)
* @MWD
* Date:2013-9-4
*
* Reference: http://www.cnblogs.com/pangxiaodong/archive/2011/08/12/2136260.html
*/
package test;
import java.util.*;
public class MyStack {
/*用链表来实现栈结构*/
class Node{
int data;
Node next;
Node(){}
Node(int data,Node next){
this.data = data;
this.next = next;
}
}
Node head;
int count; //用于记录链表中的元素个数
int maxData;
Node maxNode = new Node();
Map<Integer, Node> map = new HashMap<Integer, Node>();
public MyStack(){
this.count = 0;
}
private void push(int data){
if(count == 0){
this.head = new Node(data,null);
maxData = data;
maxNode= this.
实现一个栈,获取其中最大元素,获取时间复杂度为O(1)
最新推荐文章于 2022-04-10 19:56:36 发布