堆栈的实现可以基于链表实现
它实际上只完成链表的部分功能,我们可以通过继承链表并屏蔽掉部分方法就可以了
它是一个后进先出的链表(LIFO),一个对象在插入的时候被放在整个堆栈的头部,删除也只能在头部进行
我们需要的是链表的头部插入和头部删除方法,屏蔽尾部插入和尾部删除方法,其他的类似
/**
* @(#)StackList.java
* Have classes:StackList
* Copyright 2005 Fane. All rights reserved.
* @author Fane
* @version 1.0, 8/08/05
* @since 1.0
*/
package person.fane.test;
/**
*
* @author Fane
*
* TODO
* 2005-08-01
* 堆栈实现类
*
*/
public class StackList extends MyList
{
/*
* 第一个节点
*/
private ListNode firstNode;
/*
* 最后一个节点
*/
private ListNode lastNode;
/*
* 堆栈的名字
*/
private String name;
/**
* 初始化堆栈
* @param s
*/
public StackList (String s)
{
this.name = s;
this.lastNode = null;
this.firstNode = null;
}
public StackList()
{
this("mylist");
}
/**
* 在堆栈前面插入元素
* @param insertItem
*/
public void insertAtFront(Object insertItem)
{
if(isEmpty())
{
this.lastNode = new ListNode(insertItem);
this.firstNode = new ListNode(insertItem);
}else
{
this.firstNode = new ListNode(insertItem,this.firstNode);
}
}
/**
* 从堆栈头部删除元素
* @return
* @throws EmptyMyListException
*/
public Object removeFromFront()throws EmptyMyListException
{
Object removeItem = null;
if(isEmpty())
throw new EmptyMyListException(this.name);
removeItem = this.firstNode.data;
if(this.firstNode.equals(this.lastNode))
{
this.lastNode =null;
this.firstNode = null;
}else
{
this.firstNode = this.firstNode.next;
}
return removeItem;
}
/**
* 判断堆栈是否为空
* @return
*/
public boolean isEmpty()
{
return this.firstNode == null;
}
/**
* 输出堆栈的各个元素
*
*/
public void print()
{
if(isEmpty())
{
System.out.println("Empty "+this.name);
return;
}
System.out.print("The "+this.name+ " is: ");
ListNode current = this.firstNode;
while(current != null)
{
System.out.print(current.data.toString()+" ");
current = current.next;
}
System.out.println();
System.out.println();
}
}