数据结构之栈(java版)
来源:互联网 发布:情定三生知夏恢复记忆 编辑:程序博客网 时间:2024/05/29 13:58
本文力求简洁,只包含基础的栈功能,不想将大片的代码展示出来,让读者兴趣索然,阅读起来也十分费力,如有需要可以自行添加相关功能比如java.util.Stack
包中的Stack类包含的peek()
,empty()
等等函数. 能力有限,有误之处还请不吝赐教
定义内部类用于存储栈元素
class Node { private Node below; //指向下一个栈元素的reference private T type; //泛型元素 public Node(Node below, T type) { this.below = below; this.type = type; } }
Push()方法
public void push(T element) { if (top == null) { Node node = new Node(null, element); this.top = node; this.base = node; length++; } else { Node node = new Node(top, element); this.top = node; length++; } }
pop()方法
public T pop() { if (top != null) { Node temp = top; if (temp.below != null) { top = temp.below; length--; } else { this.base=null; this.top=null; length=0; } return temp.type; } else return null; } public int getLength() { return length; }
整体代码比较简单,这里不再赘述,有一定java基础的应该都能够看懂
整体代码
public class MyStack<T> { private Node base; private Node top; private int length = 0; class Node { private Node below; private T type; public Node(Node below, T type) { this.below = below; this.type = type; } } public void push(T element) { if (top == null) { Node node = new Node(null, element); this.top = node; this.base = node; length++; } else { Node node = new Node(top, element); this.top = node; length++; } } public boolean isEmpty(){ if(base==null){ return true; }else return false; } public T pop() { if (top != null) { Node temp = top; if (temp.below != null) { top = temp.below; length--; } else { this.base=null; this.top=null; length=0; } return temp.type; } else return null; } public int getLength() { return length; } @Override public String toString() { StringBuffer sb = new StringBuffer(); Node current = top; while (current != null) { sb = sb.append("/"+current.type); current = current.below; } return sb.toString(); } public static void main(String[] args) { MyStack<String> ms=new MyStack<>(); System.out.println(ms.getLength()); ms.push("value1"); ms.push("value2"); ms.push("value3"); System.out.println(ms.getLength()); System.out.println(ms.pop()); System.out.println(ms.pop()); System.out.println(ms.getLength()); System.out.println(ms.toString()); } }
0 0
- 数据结构之栈(java版)
- 数据结构之栈(java版)
- java数据结构之栈
- java数据结构之栈
- java数据结构之栈
- 数据结构java版之线性表,栈
- 数据结构java版之《栈和队列》
- 数据结构之-栈(Java实现)
- 数据结构之--栈(Java代码)
- 数据结构之顺序表(java版)
- Java 数据结构之 Stack(栈)
- java 数据结构一 之栈
- JAVA 数据结构之栈实现
- Java数据结构之链式栈
- Java数据结构实现之栈
- 数据结构java版之《数组》
- 数据结构之堆(java)
- JAVA版数据结构之栈的链式存储实现
- sql server 存入中文前加N
- 深入PHP面向对象、模式与实践——高级特性(1)
- 银行拆借利率报价
- 多线程中同步异步函数与串行并发队列的组合情况
- Could not obtain transaction-synchronized Session for current thread 报错在spring注解定时任务上的处理
- 数据结构之栈(java版)
- Ubuntu14.04安装mysql-python(MySQL)
- Java中内存分配和回收策略、新生代、老年代
- 题目1007:奥运排序问题
- 记一次JSON到前台乱码的解决方案
- layout_marginRight不起作用
- springMVC--4种映射处理器handlerMapping
- GCC C语言处理主要函数之init_pragma
- yii2.0 数据库关联查询