本文主要是介绍(学习java)链栈结构的简单实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//链栈结构
public class myStackNode {public static void main(String[] args) {StackNode<Integer> S = new StackNode<Integer>();S.stackPop();S.listStack();}//建立链栈public static class StackNode<T>{//top指针指向栈顶private Node top;//栈的长度private int size;//结点类private class Node{private T data;//前驱结点private Node prior;public Node(){}public Node(T data,Node node){this.data = data;this.prior = node;}}public StackNode(){top = null;}//建立空栈并在栈顶添加一个元素public StackNode(T element){top = new Node(element,null);size++;} //入栈public void stackPush(T element){top = new Node(element,top);size++;}public T stackPop(){if(top == null){System.out.println("空栈");return null;}else{T data = top.data;Node old = top;top = top.prior;old.prior = null;size--;return data;}}//遍历链表public void listStack(){Node temp = top;if(size==0){System.out.println("空栈");System.out.println("栈的长度" + size);}else if(size == 1){System.out.println(top.data);System.out.println("栈的长度" + size);}else{while (temp.prior != null){System.out.print(temp.data + " <- ");temp = temp.prior; }System.out.println(temp.data);System.out.println("栈的长度" + size);}}}}
这篇关于(学习java)链栈结构的简单实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!