栈——链表实现

来源:互联网 发布:淘宝上的鞋子味道刺鼻 编辑:程序博客网 时间:2024/05/18 14:43

首先创建栈结点类


public class StackNode<T> {StackNode<T> pre;StackNode<T> next;T data;/** * 构造空结点 * @param args */public StackNode() {this(null, null, null);}/** * 传入数据构造结点 * @param args */public StackNode(T data, StackNode<T> pre, StackNode<T> next) {this.data = data;this.pre = pre;this.next = next;}/** * 获得结点数据 * @param args */public T getData() {return this.data;}//public static void main(String[] args) {//StackNode<String> sn = new StackNode<String>("VV", null, null);//System.out.println(sn.data);////}}


栈实现代码:


import java.util.Stack;public class LinkStack<T> {private LinkStack<T> stack;private int n; //链栈中实际元素个数private int DEFAULT_SIZE;private StackNode<T> topNode;/** * 构造链栈 * @param args */public LinkStack() {this.stack = null;this.n = 0;this.topNode = null;}/** * 判断栈是否为空 * @param args */public boolean isEmpty() {return (this.n ==0? true:false);}/** * 获得栈长度 */public int getLength() {return this.n;}/** * 入栈 * @param args */public boolean push(T data) {if(this.isEmpty()) {StackNode node = new StackNode(data, null, null);this.topNode = node;n ++;}else {StackNode node = new StackNode(data, topNode, null);this.topNode = node;n ++;}return true;}/** * 出栈 * @param args */public T pop() {if(this.n==0) {System.out.println("栈为空!");return null;}T pop_data = topNode.data;StackNode<T> temp = this.topNode.pre;this.topNode.pre = null;this.topNode.data = null;this.topNode = temp;this.n --;System.gc();return pop_data;}/** * 清空栈 * @param args */public boolean clear() {StackNode<T> temp = new StackNode<T>();while(this.topNode.data!=null) {if(this.topNode.pre!=null)temp = this.topNode.pre;this.topNode.pre = this.topNode.next = null;this.topNode.data = null;topNode = temp;}return true;}public static void main(String[] args) {LinkStack<String> ls = new LinkStack<String>();System.out.println(ls.isEmpty());for(int i=1; i<=10; i++) {ls.push(i + "");}System.out.println(ls.getLength());System.out.println(ls.pop());System.out.println(ls.getLength());System.out.println(ls.clear() + " " +ls.getLength());}}


0 0
原创粉丝点击