栈和队列的实现
2016-08-17 18:19
288 查看
数组实现栈
/** *数组实现栈,需要"数组,末端索引,初始容量" */ public class ArrayStack { //数组初始容量,由于是数组实现,需要考虑扩容问题 private int DEFAULT_CAPCITY = 10; private int[] array; private int topOfStack = -1; // 使用默认初始容量 public ArrayStack(){ array = new int[DEFAULT_CAPCITY]; } // 使用指定初始容量 public ArrayStack(int capacity){ array = new int[capacity]; } public void makeEmpty(){ topOfStack = -1; } public boolean isEmpty(){ return topOfStack == -1; } public void push(int x){ // 此时需要扩容 if(topOfStack + 1 == array.length){ array = Arrays.copyOf(array,DEFAULT_CAPCITY*2); } array[++topOfStack] = x; } public void pop(){ if(isEmpty()){ return; } topOfStack--; } }
链表实现栈
/** * 链表实现栈,链表的第一项表示栈顶元素 */ public class ListNodeStack { class ListNode{ public int element; public ListNode next; public ListNode(int theElement, ListNode theNext){ this.element = theElement; this.next = theNext; } } private ListNode topOfStack = null; public void makeEmpty(){ topOfStack = null; } public boolean isEmpty(){ return topOfStack == null; } public void push(int x){ topOfStack = new ListNode(x,topOfStack); } public void pop(){ if(isEmpty()){ return; } topOfStack = topOfStack.next; } }
链表实现队列
/** * 链表实现队列,需要"队首元素和队尾元素的引用" */ public class ListNodeQueue { class ListNode{ private ListNode next; private int element; public ListNode(int theElement, ListNode theNext){ this.element = theElement; this.next = theNext; } } private ListNode front = null; private ListNode back = null; public void makeEmpty(){ front = null; back = null; } public boolean isEmpty(){ return front == null; } public void enqueue(int x){ if(isEmpty()){ front = new ListNode(x,null); back = front; } else { back.next = new ListNode(x,null); back = back.next; } } public void dequeue(){ if(isEmpty()){ return; } else { front = front.next; } } }
相关文章推荐
- [C/C++]反转链表
- PostgreSQL教程(八):索引详解
- C#实现基于链表的内存记事本实例
- Oracle外键不加索引引起死锁示例
- oracle 索引的相关介绍(创建、简介、技巧、怎样查看) .
- 用SQL建立索引的方法步骤
- SQL2005重新生成索引的的存储过程 sp_rebuild
- SQL效率提升之一些SQL编写建议并有效利用索引
- SQLSERVER的非聚集索引结构深度理解
- SQL Server误区30日谈 第8天 有关对索引进行在线操作的误区
- SQL Server 索引介绍
- SqlServer 索引自动优化工具
- mysql 中存在null和空时创建唯一索引的方法
- C#模拟链表数据结构的实例解析
- 详解sqlserver查询表索引
- SQL 双亲节点查找所有子节点的实现方法
- 详解C#读取Appconfig中自定义的节点
- C#线程队列用法实例分析
- 优化 SQL Server 索引的小技巧
- sqlserver 索引的一些总结