博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
算法(Algorithms)第4版 练习 1.3.7
阅读量:5794 次
发布时间:2019-06-18

本文共 2630 字,大约阅读时间需要 8 分钟。

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
implements Iterable
{ 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
iterator() { return new StackIterator(); } private class StackIterator implements Iterator
{ 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
stack = new Stack
(); 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(); } } } } }

 

转载于:https://www.cnblogs.com/songdechiu/p/6513932.html

你可能感兴趣的文章
我所见的讲的最容易理解,逻辑最强的五层网络模型,来自大神阮一峰
查看>>
js实现复选框的操作-------Day41
查看>>
chrome浏览器开发者工具之同步修改至本地
查看>>
debian7 + wheezy + chromium + flashplayer
查看>>
AOP
查看>>
进阶开发——文档,缓存,ip限速
查看>>
vue中子组件需调用父组件通过异步获取的数据
查看>>
uva 11468 - Substring(AC自己主动机+概率)
查看>>
Mysql 数据备份与恢复,用户创建,授权
查看>>
Angular.js中的$injector服务
查看>>
构建之法读书笔记01
查看>>
linux - lsof 命令最佳实践
查看>>
kafka性能测试
查看>>
现实世界的Windows Azure:h.e.t软件使用Windows Azure削减50%的成本
查看>>
深入.net框架
查看>>
聚合类新闻client产品功能点详情分析
查看>>
js设置定时器
查看>>
数据库除运算
查看>>
LeetCode--112--路径总和
查看>>
DeviceIOControl与驱动层 - 缓冲区模式
查看>>