您的位置:首页 > 编程语言 > Java开发

JAVA 内部类 泛型 实现堆栈

2014-09-17 11:46 323 查看
堆栈类:

package c15;

public class LinkedStack<T> {
private static class Node<T> {
T item ;
Node<T> next ;
Node(){
item = null ;
next = null ;
}
Node (T item ,Node<T> next ){
this .item = item;
this .next = next;
}
boolean end() { return item == null && next == null ; }
}

private Node<T> top = new Node<T>();

public void push(T item){
top = new Node<T>( item, top);
}

public T pop(){
Node<T> resultNode = top ;
if (!top .end()){
top = top .next ;
}
return resultNode .item ;
}

public static void main(String[] args){
LinkedStack<Integer> sLinkedStack = new LinkedStack<Integer>();
for (int i = 0; i < 10; i++) {
sLinkedStack .push(i );
}
System. out .println(sLinkedStack .pop());
}
}


NOTE:

堆栈类设计思路:

1.使用内部类分离了结构逻辑和操作逻辑。

2.堆栈的结构特点是只能知道顶部的成员信息,每次新添加的成员都会处于堆栈的顶部,每次删除成员

都会在堆栈顶部删除。

3.堆栈结构可以简单的分为两部分,一个是顶部成员的内容,另一个是指向顶部以下的压顶部成员的指针。

4.堆栈结构必须要提供一个知道何时所有成员已经全部清除的方法。

操作的设计思路:

1.需要一个空类内容在实例化的时候填充到底部。

2.一个push():添加新成员到顶部,一个pop():把顶部成员删除

important:

堆栈的下一个的意思一般都是指该成员的前一个成员,因为在堆栈的角度来说,他自己永远都不会自到自己后面的成员是谁。每一个成员都只会知道自己的前面是谁。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: