堆栈的链式存储称为链栈。
代码下载:
public class Stack<T> implements StackInterface<T> {
private Node<T> top; //链表首结点引用
private int size; //栈的大小
public Stack() {
top = null;
size = 0;
}
//返回堆栈的大小
public int getSize() {
return size;
}
//判断堆栈是否为空
public boolean isEmpty() {
return size==0;
}
//数据元素e入栈
public void push(T t) {
Node<T> q = new Node<T>(t,top);
top = q;
size++;
}
//栈顶元素出栈
public T pop() throws StackEmptyException {
if (size<1)
throw new StackEmptyException("错误,堆栈为空。");
T t = top.getData();
top = top.getNext();
size--;
return t;
}
//取栈顶元素
public T peek() throws StackEmptyException {
if (size<1)
throw new StackEmptyException("错误,堆栈为空。");
return top.getData();
}
//测试:将10进制数转换成8进制数
public static void main(String args[]){
System.out.println("请输入十进制数");
java.util.Scanner in=new java.util.Scanner(System.in);
int i=in.nextInt();
int temp=i;
Stack<Integer> s=new Stack<Integer>();
while(i>0){
s.push(i%8);
i=i/8;
}
System.out.println("十进制数"+temp+"转换成8进制数是:");
while(!s.isEmpty())
System.out.print(s.pop());
}
}
interface StackInterface<T> {
//返回堆栈的大小
public int getSize();
//判断堆栈是否为空
public boolean isEmpty();
//数据元素e入栈
public void push(T t);
//栈顶元素出栈
public T pop() throws StackEmptyException;
//取栈顶元素
public T peek() throws StackEmptyException;
}
class Node< T> {
private T data;
private Node< T> next;
public Node() {
this(null,null);
}
public Node(T data, Node< T> next) {
this.data = data;
this.next = next;
}
public T getData(){
return data;
}
public void setData(T data){
this.data=data;
}
public Node<T> getNext(){
return this.next;
}
public void setNext(Node<T> next){
this.next=next;
}
}
//堆栈为空时出栈或取栈顶元素抛出此异常
class StackEmptyException extends RuntimeException{
public StackEmptyException(String err) {
super(err);
}
}
代码下载: