首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

栈的兑现

2012-09-22 
栈的实现栈的实现:import java.io.*//栈中的每个节点class Element{//指向下一个节点private Element nex

栈的实现

栈的实现:

import java.io.*;//栈中的每个节点class Element{//指向下一个节点private Element next;//节点中的对象private Object  value;public Element getNext() {return next;}public Object getValue() {return value;}public Element(){this.next=null;this.value=null;}//构造方法public Element(Element next,Object value){this.next=next;this.value=value;}}//栈结构public class MyStack { //指向最顶的栈节点 Element top; //栈中节点个数 int     count;  //初始化栈 public MyStack() { this.top=null; count=0; } //压入 public void push(Object value) { Element e=new Element(this.top,value);  this.count++; this.top=e; } //弹出 public Object pop() { Element e=this.top; if(this.top!=null) { this.count--; this.top=this.top.getNext(); return e.getValue(); } else return null; } //查看栈顶节点 public Object get_top() { if(this.top!=null) { return this.top.getValue();  } else { return null; } } //栈中节点数 public int get_count() { return this.count; }      public static void main(String args[])     {      MyStack s=new MyStack();      Integer i=new Integer("1");      String j=new String("2345abcdej");      s.push(i);      s.push(j);      System.out.println("栈节点数:"+s.get_count());      System.out.println("查看栈顶:"+s.get_top());      System.out.println("弹出栈顶:"+s.pop());      System.out.println("---------------------------");      System.out.println("栈节点数:"+s.get_count());      System.out.println("查看栈顶:"+s.get_top());      System.out.println("弹出栈顶:"+s.pop());      System.out.println("---------------------------");      System.out.println("栈节点数:"+s.get_count());      System.out.println("查看栈顶:"+s.get_top());      System.out.println("弹出栈顶:"+s.pop());      System.out.println("---------------------------");     }}

?

热点排行