ITPub博客

首页 > Linux操作系统 > Linux操作系统 > JAVA实现stack2

JAVA实现stack2

原创 Linux操作系统 作者:cppsoldier 时间:2008-10-28 10:53:09 0 删除 编辑

package com.hb.ds.stack;


class Node {

 public Node previous;
 public T value;
 
 public Node(T value, Node previous){
  this.previous = previous;
  this.value = value;
 }
 
 public Node(T value){
  this.previous = null;
  this.value = value;
 }
}

class Stack {

 private int count = 0;

 public Node first = null;

 /**
  * 进栈
  * @param o
  */
 public void push(T o) {
  first = new Node(o, first); //让Node的next指针指向first这个Node ,然后在让first指向这个新建立的Node (这句很关键,必须理解)
          //这样写好理解一些:Node temp = new Node(o,first);
          //               first = temp;
  count++;
  System.out.println("数据入栈成功 " + o);
 }

 /**
  * 出栈
  * @return
  */
 public T pop() {
  if (first == null) {
   throw new NullPointerException();
  } else {
   T temp = first.value;
   System.out.println("数据正在出栈成功"+first.value);
   first = first.previous; //关键的一句
   count--;

   System.out.println("数据出栈成功");
   return temp;
  }
 }
 
 public void clear(){
  while(count!=0){
   pop();
  }
 }
}

 

public class StackTest {

 public static void main(String[] args){
  Stack s = new Stack();
  s.push("23");
  s.push("24");
  s.push("25");
  s.push("26");
  
  s.pop();
  
  s.clear();
 }
}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/9474419/viewspace-478450/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: JAVA实现Stack
下一篇: JAVA的IO
请登录后发表评论 登录
全部评论

注册时间:2008-10-09

  • 博文量
    18
  • 访问量
    16448