算法(Algorithms)第4版 练习 1.3.7
2024-09-08 04:39:53
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();
}
} } } }
最新文章
- git 出错误“值对于Uint32太大或太小”
- RPC原来就是Socket——RPC框架到dubbo的服务动态注册,服务路由,负载均衡演化
- C#+ AE 注意问题汇总(不断更新)
- laravel框架总结(十三) -- redis使用
- IL指令大全(转)
- mysql列转行
- 读取input:file的路径并显示本地图片的方法
- 暴力/set Codeforces Round #291 (Div. 2) C. Watto and Mechanism
- jquery怎么实现跨域的访问呢?与别人提供的接口连接
- 8-14-Exercise(博弈:HDU 1846 &; HDU 1527 )
- Oracle数据库之创建表结构
- python2.X和python3.X在同一平台下的切换技巧
- ASP.NET成员资格与角色管理配置内容
- java变量初始化
- Tween 若干年后我尽然还要学数学 曲线到底是什么鬼啊
- instanceof 是如何工作的
- 如何使用phpstudy本地搭建多站点(每个站点对应不同的端口)
- Swift tableview自带的刷新控件
- MySQL存储引擎简单介绍
- 201771010118马昕璐《面向对象程序设计java》第八周学习总结
热门文章
- is_callable — 检测参数是否为合法的可调用结构
- Atitit.&#160;如何判断软件工程师&#160;能力模型&#160;程序员能力模型&#160;&#160;项目经理能力模型
- [码海拾贝 之Perl]在字符串数组中查找特定的字符串是否存在
- iOS swift 给MBProgressHUD添加分类
- C#多线程简单例子讲解
- cordova ios升级插件
- Django开发之html交互
- Java多线程之~~~~synchronized 方法
- phpstudy配置php7.1.11 + phpstudy nginx伪静态
- Java数据结构-线性表之顺序表ArrayList