java 数据结构 栈的实现

java数据结构之栈的实现,可是入栈,出栈操作;

/**
 * java数据结构之栈的实现
 * 2016/4/26
 **/
package cn.Link;

public class Stack{
    Node tail = new Node(); 
    Node nowNode = new Node();   //永远指向栈顶
    int size;
    Stack(){};
    Stack(String date){
        this.tail.date = date;
        this.tail.next = null;
        this.nowNode.next = this.tail;
        this.size = 1;
    }

    //节点类
    class Node{
        String date;
        Node next;
        Node(){};
        Node(String date){
            this.date = date;
        }
    }

    //向栈中插入数据
    public void Push(String date){
        Node preNode = new Node(date);
        preNode.next = this.nowNode.next;
       this.nowNode.next = preNode; 
       this.size++;
       System.out.println("数据"+date+"被入栈");
    }

    //出栈操作
    public void Pop(){
        if(this.nowNode.next != this.tail){
          System.out.println("数据"+this.nowNode.next.date+"被移除栈");
          this.nowNode.next = this.nowNode.next.next;   
        }else{
            nowNode.next = null;
            System.out.println("此栈没有数据,数据为空");
        }
        this.size--;
    }

    //遍历栈输出
    public void PrintStack(){
        Node preNode = new Node();
        preNode.next = this.nowNode.next;
        System.out.print("遍历输出栈: ");
        while(preNode.next != null){
            System.out.print(" -->"+preNode.next.date);
            preNode.next = preNode.next.next;
        }
        System.out.println("+++++++++++当前栈的长度为"+this.size);
    }

    //清空栈
    public void clear(){
        this.nowNode.next = null;
        this.tail = null;
        this.size = 0;
        System.out.println("栈已被清空");

    }

    public static void main(String[] args){
       Stack stack = new Stack("sum1");
        stack.Push("sum2");
        stack.Push("sum3");
        stack.Push("sum4");
        stack.Push("sum5");
        stack.Push("sum6");
        stack.Pop();
        stack.Push("sum7");
        stack.Push("sum8");
        stack.PrintStack();
        stack.clear();
    }
}
原文地址:https://www.cnblogs.com/snail-lb/p/5437509.html