Java8实现任意参数的链栈

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java8实现任意参数的链栈

因吉   2020-10-27 我要评论

1、实现功能

1)push():入栈;
2)pop():出栈;
3)getSize():获取栈大小;
4)display():展示栈。

以一下测试进行特别说明:

 /**
   * The main function.
 */
  public static void main(String[] args) {
    MyLinkedStack <Character> test = new MyLinkedStack<>();
    test.push('2');
    test.push('+');
    test.push('-');
    test.pop();
    test.push('(');
    test.display();
}

输出如下,即输出顺序为栈顶、栈顶下一个…

The linked stack is:
[(, +, 2]

2、代码

package DataStructure;

/**
 * @author: Inki
 * @email: inki.yinji@qq.com
 * @create: 2020 1026
 * @last_modify: 2020 1026
 */

public class MyLinkedStack <AnyType> {

  /**
   * Only used to store the head node.
   */
  private SingleNode<AnyType> head = new SingleNode(new Object());

  /**
   * The single linked list current size.
   */
  private int size = 0;

  /**
   * Push element to the end of the list.
   * @param:
   *   paraVal: The given value.
   */
  public void push(AnyType paraVal) {
    SingleNode <AnyType> tempNode = new SingleNode<>(paraVal);
    tempNode.next = head.next;
    head.next = tempNode;
    size++;
  }//Of push

  /**
   * Pop the last element.
   * @return:
   *   The popped value.
   */
  public AnyType pop(){

    if (size == 0) {
      throw new RuntimeException("The stack is empty.");
    }

    AnyType retVal = head.next.val;
    head.next = head.next.next;
    size--;
    return retVal;
  }//Of pop

  /**
   * Get the current size of the single linked list.
   * @return:
   *   The current size of the single linked list.
   */
  public int getSize() {
    return size;
  }//Of getSize

  /**
   * Display the single linked list.
   */
  public void display() {

    if (size == 0) {
      throw new RuntimeException("The stack is empty.");
    }//Of if

    System.out.print("The linked stack is:\n[");
    SingleNode <AnyType> tempNode = head;
    int i = 0;
    while (i++ < size - 1) {
      tempNode = tempNode.next;
      System.out.printf("%s, ", tempNode.val);
    }//Of while
    System.out.printf("%s]\n", tempNode.next.val);
  }//Of display

  /**
   * The main function.
   */
  public static void main(String[] args) {
    MyLinkedStack <Character> test = new MyLinkedStack<>();
    test.push('2');
    test.push('+');
    test.push('-');
    test.pop();
    test.push('(');
    test.display();
  }
}//Of class MyLinkedStack


class SingleNode <AnyType>{

  /**
   * The value.
   */
  AnyType val;

  /**
   * The next node.
   */
  SingleNode<AnyType> next;

  /**
   * The first constructor.
   * @param
   *   paraVal: The given value.
   */
  SingleNode (AnyType paraVal) {
    val = paraVal;
  }//The first constructor

}//Of class SingleNode

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们