Java实现栈

栈的定义

 栈(stack)是限定在表尾进行插入和删除操作的线性表.
 栈顶和栈底:允许插入和删除的一端为栈顶(Top),相对另一端为栈底(Buttom).
 空栈:不含任何数据的栈称为空栈.
 栈又称为先进后出(LIFO)的线性表

栈的操作

入栈:插入元素;
出栈:获取元素并移除
这里写图片描述

Java实现栈

定义节点

节点包括数据和指向下一个节点的引用

class Node{ 
    public Integer data;
    public Node next;   
    public Node(Integer data) {
        super();
        this.data = data;
    }
}

定义栈

分别为指向栈顶元素的引用和栈的长度.

class Stack{
    private Node top;
    private Integer size = 0;
}

获取栈顶元素

public Integer  getTop(){       
    return top.data;
}

pop元素

获取并删除栈顶元素

public Integer pop() {      
    if(top == null) {
        return null;
    }
    else {
        Node n = top;
        top = n.next;
        Integer data = n.data;
        n  = null;
        return data;            
    }
}

push元素

public void push(Integer data) {
    Node n = new  Node(data);
    if(top == null) {
        top = n;
    }
    else {
        n.next = top;
        top  = n;
    }   
    size++;
}

清空栈

public void  clean() {
    while(top != null ) {
        Node n = top;
        top = n.next;
        n = null;
    }
    size = 0;
}

转化为String

public String toString() {
    String str = "The stack data is :";
    Node n = top; 
    while(n !=  null) {
        str += n.data + "  ";
        n = n.next;
    }
    return str;
}

测试

public static void main(String[] args) {
        // TODO Auto-generated method stub
    Stack stack = new Stack();

    stack.push(5);
    stack.push(10);
    stack.push(15);
    stack.push(25);

    System.out.println(stack.toString());       
    System.out.println("Top data :" + stack.getTop());
    System.out.println("The size is :" + stack.getSize());

    System.out.println("pop a data");
    stack.pop();
    System.out.println(stack.toString());

    System.out.println("clean the stack");      
    stack.clean();
    System.out.println(stack.toString());

}

输出

The stack data is :25  15  10  5  
Top data :25
The size is :4
pop a data
The stack data is :15  10  5  
clean the stack
The stack data is :
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值