您的位置:首页 > 编程语言 > Java开发

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

2017-05-23 19:24 405 查看
请编写代码实现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());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐