package com.qiusongde;

import java.util.Iterator;
import java.util.NoSuchElementException; import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut; public class Stack<Item> implements Iterable<Item> { private Node first;
private int n; private class Node {
Item item;
Node next;
} public Stack() {
first = null;
n = 0;
} public void push(Item item) {
Node oldfirst = first; first = new Node();
first.item = item;
first.next = oldfirst; n++;
} public Item pop() { if(isEmpty())
throw new NoSuchElementException("Stack is empty"); Item item = first.item;
first = first.next;
n--; return item;
} //1.3.7
public Item peek() {
if(isEmpty())
throw new NoSuchElementException("Stack is empty"); return first.item;
}
public boolean isEmpty() {
return first == null;
} public int size() {
return n;
} @Override
public Iterator<Item> iterator() { return new StackIterator();
} private class StackIterator implements Iterator<Item> { private Node current = first; @Override
public boolean hasNext() {
return current != null;
} @Override
public Item next() {
if(!hasNext())
throw new NoSuchElementException("Stack is empty"); Item item = current.item;
current = current.next; return item;
} @Override
public void remove() {
throw new UnsupportedOperationException("Stack don't support remove");
} } public static void main(String[] args) { Stack<String> stack = new Stack<String>();
StdOut.println("Initialized size:" + stack.size()); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (!item.equals("-")) { stack.push(item);
StdOut.println("push success:" + item + " size:" + stack.size()); StdOut.print("Left on stack: ");
for (String s : stack) {
StdOut.print(s + " ");
}
StdOut.println(); } else {
if(stack.isEmpty())
StdOut.println("pop error, stack empty");
else {
StdOut.println("pop success:" + stack.pop() + " size:" + stack.size()); StdOut.print("Left on stack: ");
for (String s : stack) {
StdOut.print(s + " ");
}
StdOut.println();
}
} } } }

最新文章

  1. git 出错误“值对于Uint32太大或太小”
  2. RPC原来就是Socket——RPC框架到dubbo的服务动态注册,服务路由,负载均衡演化
  3. C#+ AE 注意问题汇总(不断更新)
  4. laravel框架总结(十三) -- redis使用
  5. IL指令大全(转)
  6. mysql列转行
  7. 读取input:file的路径并显示本地图片的方法
  8. 暴力/set Codeforces Round #291 (Div. 2) C. Watto and Mechanism
  9. jquery怎么实现跨域的访问呢?与别人提供的接口连接
  10. 8-14-Exercise(博弈:HDU 1846 &amp; HDU 1527 )
  11. Oracle数据库之创建表结构
  12. python2.X和python3.X在同一平台下的切换技巧
  13. ASP.NET成员资格与角色管理配置内容
  14. java变量初始化
  15. Tween 若干年后我尽然还要学数学 曲线到底是什么鬼啊
  16. instanceof 是如何工作的
  17. 如何使用phpstudy本地搭建多站点(每个站点对应不同的端口)
  18. Swift tableview自带的刷新控件
  19. MySQL存储引擎简单介绍
  20. 201771010118马昕璐《面向对象程序设计java》第八周学习总结

热门文章

  1. is_callable — 检测参数是否为合法的可调用结构
  2. Atitit.&#160;如何判断软件工程师&#160;能力模型&#160;程序员能力模型&#160;&#160;项目经理能力模型
  3. [码海拾贝 之Perl]在字符串数组中查找特定的字符串是否存在
  4. iOS swift 给MBProgressHUD添加分类
  5. C#多线程简单例子讲解
  6. cordova ios升级插件
  7. Django开发之html交互
  8. Java多线程之~~~~synchronized 方法
  9. phpstudy配置php7.1.11 + phpstudy nginx伪静态
  10. Java数据结构-线性表之顺序表ArrayList