打印本文 打印本文  关闭窗口 关闭窗口  
Java版本和C++版本简单Stack程序
作者:佚名  文章来源:不详  点击数  更新时间:2008/4/18 14:38:36  文章录入:杜斌  责任编辑:杜斌

  Java版本:

  源代码Stack.java

以下是引用片段:
  package org;
  public class Stack ...{
  public static class Link ...{
  protected Object data;
  protected Link next;
  public Link(Object data, Link next) ...{
  this.data = data;
  this.next = next;
  }
  }
  private Link head = null;
  public void push(Object data) ...{
  head = new Link(data, head);
  }
  public Object peek() ...{
  return head.data;
  }
  public Object pop() ...{
  if (head == null)
  return null;
  Object o = head.data;
  head = head.next;
  return o;
  }
  } 测试代码StackTest.java
  package org;
  import junit.framework.TestCase;
  public class StackTest extends TestCase ...{
  public void test1() ...{
  Stack s = new Stack();
  assertEquals(null, s.pop());
  s.push("a");
  s.push("b");
  assertEquals("b", s.peek());
  assertEquals("b", s.pop());
  assertEquals("a", s.pop());
  assertEquals(null, s.pop());
  }
  public void test2() ...{
  Stack s = new Stack();
  assertEquals(null, s.pop());
  s.push(new Integer(1));
  s.push(new Integer(2));
  assertEquals(2, ((Integer)s.peek()).intValue());
  assertEquals(2, ((Integer)s.pop()).intValue());
  assertEquals(1, ((Integer)s.pop()).intValue());
  assertEquals(null, s.pop());
  }
  }

打印本文 打印本文  关闭窗口 关闭窗口