码迷,mamicode.com
首页 > 编程语言 > 详细

java 数据结构 栈的实现

时间:2016-04-27 09:37:27      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

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();
    }
}

 

java 数据结构 栈的实现

标签:

原文地址:http://www.cnblogs.com/snail-lb/p/5437509.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!