java 编写代码实现Stack类 ,采用单链表

来源:互联网 发布:怎么在淘宝投诉卖家 编辑:程序博客网 时间:2024/05/18 18:19
请编写代码实现Stack类,该类能够实现后进先出的堆栈功能,要求实现的方法包括:
   Stack(int) – 实例化指定深度的栈
   boolean push(E item) – 向栈顶压入对象,成功返回true,栈已满返回false
   E pop() – 从栈顶移除对象并返回,如栈为空返回null
   E peek() – 查看并返回栈顶的对象,如栈为空返回null
   int size() – 返回堆栈中当前的元素数量
   int depth() – 返回当前堆栈深度
package datastruct.stack;class Node<E>{Node <E> next=null;E data;public Node(E data) {this.data=data;}}//采用链表实现栈public class Stack<E> { int depth;//栈的深度  public Stack(int i) {this.depth=i;}  Node<E> top=null;    //将元素压入栈中  public boolean push(E data) {  if (size()<depth) {  Node<E> newNode=new Node<E>(data);  newNode.next=top;  top=newNode;  return true;  }return false;}    //读取栈中的头结点,不删除头结点  public E peek() {  if (top==null) {return null;}return top.data;}  //获取栈中的头结点,并删除头结点  public E pop() {  if (top==null) {return null;}  Node<E> tmp=top;  top=top.next;return tmp.data;}  //栈的元素个数  public int size(){  int leng=0;  Node tmeNode=top; while(tmeNode!=null) { tmeNode=tmeNode.next;   leng++; }  return leng;  }    //当前栈的深度  public int depth() {return this.depth;}  public static void main(String[] args) {Stack stack=new Stack<>(2);System.out.println(stack.push(1));System.out.println(stack.push(2));System.out.println(stack.push(3));System.out.println(stack.size());System.out.println(stack.pop());System.out.println(stack.pop());System.out.println(stack.pop());System.out.println(stack.depth());}}

原创粉丝点击