Java8实现任意参数的链栈
更新时间:2020年10月27日 17:12:50 作者:因吉
这篇文章主要为大家详细介绍了Java8实现任意参数的链栈,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Java8实现任意参数的链栈,供大家参考,具体内容如下
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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章
高级数据结构及应用之使用bitmap进行字符串去重的方法实例
今天小编就为大家分享一篇关于高级数据结构及应用之使用bitmap进行字符串去重的方法实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧2019-02-02Java中对list map根据map某个key值进行排序的方法
今天小编就为大家分享一篇Java中对list map根据map某个key值进行排序的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2018-07-07解析Java中的Timer和TimerTask在Android中的用法和实例
本篇文章主要介绍了解析Java中的Timer和TimerTask在Android中的用法,主要介绍了Timer和TimerTask的用法,有需要的可以了解一下。2016-11-11
最新评论