源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

java中stack(栈)的使用代码实例

  • 时间:2020-06-02 18:27 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:java中stack(栈)的使用代码实例
java中stack类继承于vector,其特性为后进先出(lastinfirstout). 入栈和出栈实例图: [img]http://files.jb51.net/file_images/article/201712/20171212113138988.png?20171112113148[/img] 实例图的java代码实例:
package com.lanhuigu.java.ListTest;
import java.util.Stack;
public class StackTest {
 public static void main(String[] args) {
  Stack<String> staffs = new Stack<String>();
  // 入栈顺序: a,b,c,d,e 
  staffs.push("a");
  staffs.push("b");
  staffs.push("c");
  staffs.push("d");
  staffs.push("e");
  // 出栈顺序: e,d,c,b,a 
  while( !staffs.isEmpty()) {
   System.out.print(staffs.pop() + " ");
  }
 }
}
程序运行结果: edcba Stack类中方法: 官网API: [img]http://files.jb51.net/file_images/article/201712/20171212113310837.png?20171112113323[/img] 方法分析: empty():判断栈是否为空,为空返回true,否则返回false peek():取出栈顶元素,但是不从栈中移除元素 pop():取出栈顶元素,并且将其从栈中移除 push(Eitem):元素入栈 search(Objecto):在栈中查找元素位置,位置从栈顶开始往下算,栈顶为1, 依次往下数到所查找元素位置,如果所查找元素在栈中不存在,则返回-1。 关于这几个方法的实例:
package com.lanhuigu.java.ListTest;
import java.util.Stack;
public class StackMethodTest {
 public static void main(String[] args) {
  Stack<String> staffs = new Stack<String>();
  // 入栈顺序: a,b,c,d,e 
  staffs.push("a");
  staffs.push("b");
  staffs.push("c");
  staffs.push("d");
  staffs.push("e");
  System.out.println("empty():" + staffs.empty());
  System.out.println("peek():" + staffs.peek());
  System.out.println("search(Object o):" + staffs.search("a"));
  System.out.println("search(Object o):" + staffs.search("e"));
  System.out.println("search(Object o):" + staffs.search("no"));
  // 出栈顺序: e,d,c,b,a 
  while( !staffs.isEmpty()) {
   System.out.print(staffs.pop() + " ");
  }
  System.out.println("=====空栈中使用方法=======");
  System.out.println("empty():" + staffs.empty());
  //System.out.println("peek():" + staffs.peek());// 在空栈中使用时报错,因为没有栈顶元素 
  System.out.println("search(Object o):" + staffs.search("a"));
  System.out.println("search(Object o):" + staffs.search("e"));
  System.out.println("search(Object o):" + staffs.search("no"));
  //System.out.print(staffs.pop());// 空栈中移除栈顶元素,报错
 }
}
程序运行结果: [img]http://files.jb51.net/file_images/article/201712/20171212113649279.png?2017111211370[/img] 以上几个方法是Stack继承于Vector扩展的方法,因为Stack继承于Vector,哪么Vector中的非private方法 也是Stack类的方法。 Vector中的方法,官方API_1.8: [img]http://files.jb51.net/file_images/article/201712/20171212113732031.png?20171112113747[/img] [b]总结[/b] 以上就是本文关于java中stack(栈)的使用代码实例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题。如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部