看了看以前的数据结构课本
把C语言的算法改成Java的 写了个链栈的算法 (JRE中Stack类在java.util包里)
//Coding by zhaohongliang
public class LinkStackTest ...{
public static void main(String[] args) ...{
LinkStack<Integer> ls =new LinkStack<Integer>();
Integer intgr = null;
for (int i=0;i<100;i++) ...{
intgr = new Integer(i);
ls.push(intgr);
}
while(!ls.empty()) ...{
System.out.print(ls.pop()+" ");
}
}
}
class LinkStack<T> ...{
private T data;
private LinkStack<T> next;
public LinkStack() ...{
data = null;
next = null;
}
public void push(T item) ...{
LinkStack<T> temp = next;
next = new LinkStack<T>();
next.next = temp;
next.data = item;
}
public boolean empty() ...{
return next==null ? true : false;
}
public T peek() ...{
if(empty()) throw new EmptyStackException();
return next.data;
}
public T pop() ...{
if(empty()) throw new EmptyStackException();
LinkStack<T> temp = next;
next = next.next;
return temp.data;
}
}
class EmptyStackException extends RuntimeException ...{}
//在java.util包里也有EmptyStackException

本文介绍了一种使用Java实现链栈的数据结构方法。通过将原有的C语言算法转换为Java语言,作者提供了一个具体的链栈实现案例,其中包括了基本操作如push、pop等,并展示了如何用该链栈存储和读取整数。
5万+

被折叠的 条评论
为什么被折叠?



