java用链表实现栈_java用单链表实现栈的基本操作

packageEric.ADT;/***

* Title:MyStack

*

*

* Description:用单链表实现栈的基本操作

*

*

* Location:Frostburg

*

*

*@author: Eric.Chen

* @date:2017年9月24日下午7:31:28*/

public classMyStack {class Node {//定义节点

privateNode next;publicObject value;

}

Node top= null;void init() {//初始话头结点

top = newNode();

top.next= null;

top.value= null;

}public void push(Object element) {//采用头插发的方式模拟入栈

Node e = newNode();

e.value=element;if (top.next == null) {

top.next=e;

}else{

e.next=top.next;

top.next=e;

}

}public Object pop() {//弹出栈顶元素,也就是头结点后面的第一个元素

Object ele = null;if (top.next == null) {

System.out.println("栈为空!");

}else{

ele=top.next.value;

top.next= top.next.next;//移动指针。相当于删除链表中第一个元素

}returnele;

}public Object peek()//返回栈顶元素,不执行出栈操作

{if(top.next==null)

{return -1;

}else

returntop.next.value;

}public boolean isempty()//判断栈是否为空

{return top.next==null?true:false;

}public int size() {//返回栈的大小,含有的元素个数

Node temp =top;int i = 0;while (temp.next != null) {

i++;

temp=temp.next;

}returni;

}public void print() {//打印栈中存在的元素

Node temp =top;if(temp.next==null)

{

System.out.println("栈为空!");

}while (temp.next != null) {

System.out.print(temp.next.value+ " ");

temp=temp.next;

}

}public static voidmain(String[] args) {

MyStack stack= newMyStack();

stack.init();for (int i = 0; i < 5; i++) {

stack.push(i);

}/*Object ele1 = stack.pop();

Object ele2 = stack.pop();

Object ele3 = stack.pop();

Object ele4 = stack.pop();

Object ele5 = stack.pop();

System.out.println(ele1);

System.out.println(ele2);

System.out.println(ele3);

System.out.println(ele4);

System.out.println(ele5);*/Object ele1=stack.pop();

System.out.println("此次弹出的元素为:"+ele1);

System.out.print("栈中剩余的元素为:");

stack.print();

System.out.println();

System.out.println("栈顶元素为:"+stack.peek());

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值