java堆peek,Java---堆栈的三种实现

哎,面试被问住了,就记得当时学过的先进后出了,在此记录下。

(转载了一个大神回答,地址在这:https://segmentfault.com/a/1190000002516799

Stack

栈(Stack)是限制仅在表的一端进行插入和删除运算的线性表。

java 没有栈这样的数据结构,如果想利用先进后出(FILO)这样的数据结构,就必须自己实现。

要实现Stack,至少应该包括:

pop() 出栈操作,弹出栈顶元素。

push(E e) 入栈操作

peek() 查看栈顶元素

isEmpty() 栈为空

另外,实现一个栈,还应该考虑到几个问题:

栈的初始大小以及栈满以后如何新增栈空间

对栈进行更新时需要进行同步

有三种实现的方式,数组,容器,以及链表的方法。

数组:

import java.util.*;

public class StackArray{

private int[] array;//用数组实现

private int top; //栈顶指针

private final static int size = 100;

public StackArray(){

array = new int[size];

top = -1; //栈空的时候

}

//压栈

public void push(int element){

if(top == size-1){

throw new StackOverflowError();

}

else

array[++top] = element;

}

//弹栈

public int pop(){

if(top == -1){

throw new EmptyStackException();

}

return array[top--];

}

//判断是否为空

public boolean isEmpty(){

return top == -1;

}

//返回栈顶元素

public Integer peek(){

if(top == -1){

throw new EmptyStackException();

}

return array[top];

}

}

容器

public interface Stack {

public T pop();

public void push(T element);

public boolean isEmpty();

public T peek();

}

package gsm;

import java.util.*;

public class StackList implements Stack {

private List list ; //用容器实现

StackList(){

list = new ArrayList();

}

//弹栈

public T pop(){

if(this.isEmpty() == true){

throw new EmptyStackException();

}

return list.remove(list.size()-1);

}

//压栈

public void push(T element){

list.add(element);

}

//判断是否为空

public boolean isEmpty(){

return list.size() == 0;

}

//返回栈顶元素

public T peek(){

if(this.isEmpty() == true){

throw new EmptyStackException();

}

return list.get(list.size()-1);

}

}

链表

import java.util.EmptyStackException;

public class LinkedStack implements Stack{

//不用容器或者数组等数据结构存储节点

//Node定义一个节点类

private static class Node{

private U item; //存储的data

private Node next; //类似指针

Node(){

this.item = null;

this.next = null;

}

Node(U item, Node next){

this.item = item;

this.next = next;

}

boolean end(){

return item == null && next == null;

}

}

private Node top ; //栈顶指针

LinkedStack(){

top = new Node();

}

//弹栈

public T pop(){

if(this.isEmpty() == true){

throw new EmptyStackException();

}

T result = top.item;

if(!top.end())

{

top = top.next;

}

return result;

}

//压栈

public void push(T element){

top = new Node(element, top);

}

//判断是否为空

public boolean isEmpty(){

return top.end();

}

//返回栈顶元素

public T peek(){

if(this.isEmpty() == true){

throw new EmptyStackException();

}

T result = top.item;

return result;

}

}

可以发现容器果然是java的一个利器,方便高效。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值