-
C#教程之程序员必看:实现栈有这两种策略,有完整分析和代码实现(2)
本站最新发布 C#从入门到精通
试听地址 https://www.xin3721.com/eschool/CSharpxin3721/
return new ReverseArrayIterator(); 51 } 52 53 // an iterator, doesn't implement remove() since it's optional 54 private class ReverseArrayIterator implements Iterator<String> { 55 private int i = n-1; 56 public boolean hasNext() { return i >= 0; } 57 public void remove() { throw new UnsupportedOperationException(); } 58 59 public String next() { 60 if (!hasNext()) throw new NoSuchElementException(); 61 return items[i--]; 62 } 63 } 64 65 66 67 /*************************************************************************** 68 * Test routine. 69 ***************************************************************************/ 70 public static void main(String[] args) { 71 ResizingArrayStackOfStrings stack = new ResizingArrayStackOfStrings(); 72 while (!StdIn.isEmpty()) { 73 String item = StdIn.readString(); 74 if (!item.equals("-")) stack.push(item); 75 else if (!stack.isEmpty()) StdOut.print(stack.pop() + " "); 76 } 77 StdOut.println("(" + stack.size() + " left on stack)"); 78 } 79}
7
总结
试听地址 https://www.xin3721.com/eschool/CSharpxin3721/
return new ReverseArrayIterator(); 51 } 52 53 // an iterator, doesn't implement remove() since it's optional 54 private class ReverseArrayIterator implements Iterator<String> { 55 private int i = n-1; 56 public boolean hasNext() { return i >= 0; } 57 public void remove() { throw new UnsupportedOperationException(); } 58 59 public String next() { 60 if (!hasNext()) throw new NoSuchElementException(); 61 return items[i--]; 62 } 63 } 64 65 66 67 /*************************************************************************** 68 * Test routine. 69 ***************************************************************************/ 70 public static void main(String[] args) { 71 ResizingArrayStackOfStrings stack = new ResizingArrayStackOfStrings(); 72 while (!StdIn.isEmpty()) { 73 String item = StdIn.readString(); 74 if (!item.equals("-")) stack.push(item); 75 else if (!stack.isEmpty()) StdOut.print(stack.pop() + " "); 76 } 77 StdOut.println("(" + stack.size() + " left on stack)"); 78 } 79}
以上总结了栈的两种基本实现方法,都是借助数组实现,一种是静态的,另一种可以动态扩容。这是最基本的实现思路,可以仔细体会下,能写出这些代码来,如果在面试中问到栈的知识,告诉面试官这些东西,会给你加不少分。
基于数组实现的栈结构都不是理想的,因为动态扩容时,每次都要复制老元素到新的位置上,这是耗费时间的。有没有更高效的实现方法呢?
请看接下来的推送。
栏目列表
最新更新
一个static和面试官扯了一个小时,舌战加
一步步到IOC
C#面向对象之继承
【asp.net core 系列】6 实战之 一个项目的完
linux常用指令和一些选项的汇总
centos7下安装mysql6初始化安装密码
ubuntu之命令相关问题
文件系统格式化和挂载
关于Linux下内存和Swap
phpize安装php扩展(本文章以php7扩展mbstr
php安装扩展时报错:make: *** [mbstring.lo]
php多版本:已存在php5场景下,编译安装
编译安装apache2.2对应的mod_proxy_fcgi.so模块
linux修改环境变量分析
[apue] epoll 的一些不为人所注意的特性
树莓派使用 OLED 屏显示图片及文字
容器技术之Dockerfile(三)
【原创】Linux中断子系统(二)-通用框架
C# 在Word中添加Latex 数学公式和符号
inncheck命令 – 检查语法
SQL SERVER查询数据库所有表的大小,按照记
使用 SQL 服务器时,"评估期已过期"错
sql server无法连接本地服务器
使用sql语句创建表
VB操作Access数据库小记 ————————
access数据库远程连接
java web操作Access数据库
数据库学习总结(1)
二级Access数据库大纲知识要点
链接表的意义