当前位置: 移动技术网 > IT编程>开发语言>Java > java 实现链栈存储的方法

java 实现链栈存储的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论
如下所示: package com.learn.algorithm.linkstack; /** * 链栈实现 * @author jiekun.cui

如下所示:

package com.learn.algorithm.linkstack;
/**
 * 链栈实现
 * @author jiekun.cui
 * @param <t>
 */
public class linkstack<t> {

  private linkstack<t>.node<t> top = new node<t>();
  private int size=0;
  
  /**
   * 进栈
   * @param t
   * @return ;
   */
  public boolean push(t t){
    
    if ( isempty() ) {
      top.next = new node<t>(t);
      
    } else {
      node<t> newnode = new node<t>(t, top.next);
      top.next = newnode;
    }
    size ++ ;
    return true;
  }
  
  /**
   * 出栈
   * @param t
   * @return
   */
  public t pop(){
    
    if ( isempty() ) {
      return null;
    } else {
      linkstack<t>.node<t> node = top.next;
      top.next = node.next;
      size --;
      return node.gett();
    }
  }
  
  
  /**
   * 获取栈顶元素
   * @return
   */
  public t gettop(){
    if ( isempty() ) {
      return null;
    } else {
      return top.next.gett();
    }
  }
  
  
  /**
   * 判断栈是不是为空
   * @return
   */
  public boolean isempty(){
    return size() == 0;
  }
  
  /**
   * 返回栈的大小
   * @return
   */
  public int size(){
    return size;
  }
  
  
  
  
  /**
   * @author 链栈的节点类
   * @param <t>
   */
  class node<t>{
    private t t = null;
    private node<t> next = null;
    
    public node(){
      
    }
    public node(t t){
      this.t = t;
    }
    public node(t t,node<t> next){
      this.t = t;
      this.next =next;
    }
    
    
    public t gett() {
      return t;
    }
    public void sett(t t) {
      this.t = t;
    }
    
    public node<t> getnext() {
      return next;
    }
    public void setnext(node<t> next) {
      this.next = next;
    }
  }
}
package com.learn.algorithm.linkstack;

/**
 * 链栈测试
 * @author jiekun.cui
 */
public class demo {
  
  public static void main(string[] args) {
    linkstack<integer> ls = new linkstack<>();
    
    ls.push(1);
    ls.push(2);
    ls.pop();
    ls.push(4);
    ls.push(5);
    ls.push(6);
    
    
    while ( !ls.isempty() ) {
      system.out.println(ls.pop());
    }
    
  }

}

以上这篇java 实现链栈存储的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网