JAVA拾遗 - 使用Java实现数列栈和链表栈
来源:互联网 发布:古筝教学软件 编辑:程序博客网 时间:2024/05/18 01:02
最近有点忙,没来得及更新博客...正好在看Alg PartI 的公开课,就发一批课堂练习凑个数吧...
抽象
栈主要有三个功能,我们可以用一个抽象类去规定他
package StackQueueBag;/** * Created by coco1 on 2016/9/12. */public abstract class AbstructStack { public abstract boolean isEmpty(); public abstract String pop(); public abstract void push(String s);}
链表实现
链表实现就是使用节点的形式存储每一个点
package StackQueueBag;/** * Created by coco1 on 2016/9/11. *//** * all operation takes constant time in the worst case * * 16 bytes(object head) * * 8 bytes(inner class extra overhead) * * 8 bytes(reference to String) * * 8 bytes(reference to Node) * * 40 bytes per stack node -------->40N */public class LinkedListStack extends AbstructStack{ private Node first = null; private int count = 0; public class Node { String item; Node next; public Node() { } public Node(String s) { this.item = s; this.next = null; } } public int getCount() { return count; } @Override public boolean isEmpty() { return first == null; } @Override public String pop() { String item = first.item; first = first.next; count--; return item; } @Override public void push(String item) { Node n = new Node(item); n.next = first; first = n; count ++; }}
数组实现
数组实现就是使用数组去存储每一个点
package StackQueueBag;/** * Created by coco1 on 2016/9/11. *///you have to declare the lengthpublic class ArrayListStack extends AbstructStack{ private String[] item; private int first; private int count; public ArrayListStack(int n) { item = new String[n]; first = 0; count = n; } @Override public boolean isEmpty() { return first == 0; } @Override public String pop() { return item[first--];// return item[--first]; } @Override public void push(String s) { item[++first] = s;// item[first++] = s; } /** * 数组扩容或者减容 */ public void FixedCapacityStack(int addlength) { String[] copy = new String[count + addlength]; System.arraycopy(item, 0, copy, 0, Math.min(count, count + addlength)); count = count + addlength; item = copy; } public static void main(String args[]) { ArrayListStack arrayListStack = new ArrayListStack(10); arrayListStack.push("i"); arrayListStack.push("j"); arrayListStack.push("k"); arrayListStack.push("l"); System.out.print(arrayListStack.pop()); System.out.print(arrayListStack.pop()); System.out.print(arrayListStack.pop()); System.out.print(arrayListStack.pop()); System.out.print(arrayListStack.isEmpty()); }}
注意数组实现需要添加个扩容的方法(可能会需要)
0 0
- JAVA拾遗 - 使用Java实现数列栈和链表栈
- JAVA使用循环和递归方法实现斐波拉切数列
- [珠玑拾遗]之一------通俗易懂解读位向量和Java实现
- java拾遗
- Java 拾遗
- Java拾遗
- Java拾遗
- Java拾遗
- Java拾遗
- Java拾遗
- Java拾遗
- java实现斐波拉契数列
- fibonacci数列 java实现
- 斐波拉契数列-java实现
- java实现 斐波拉契数列
- Java拾遗-内部类和匿名类
- [算法拾遗]栈和队列的实现
- 排列组合数列的java实现
- J2SE必须掌握的基础知识
- linux 部署项目指令
- Swift font 的使用
- 使用Eclipse+axis2一步一步发布webservice
- Linux命令行下使用Axel多线程下载
- JAVA拾遗 - 使用Java实现数列栈和链表栈
- OC中将数组元素逆序输出的方法
- 光标悬停显示文字和执行方法
- poj1094 Sorting It All Out
- source insight增加注释宏
- MinGw在cmd下运行C
- 计算机概念:抽象和具象的关系和联系
- 使用Proxy反射类实现AOP动态代理技术
- 字串的连接最长路径查找