数据结构再回顾(二)------------堆栈

堆栈的实现可以基于链表实现

它实际上只完成链表的部分功能,我们可以通过继承链表并屏蔽掉部分方法就可以了

它是一个后进先出的链表(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();
  
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值