首页 / JAVA / Java-数据结构练习
Java-数据结构练习
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java-数据结构练习,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2401字,纯文字阅读大概需要4分钟。
内容图文
栈(stack)可以看做是特殊类型的线性表,访问、插入和删除其中的元素只能在栈尾(栈顶)进行。
队列(queue)表示一个等待的线性表,它也可以看做是一种特殊类型的线性表,元素只能从队列的末端(队列尾)插入,从开始(队列头)访问和删除。
————Java语言程序设计 进阶篇(原书第8版)
栈是先进后出(LIFO),而队列是先进先出(FIFO)。
实现栈这个数据结构的代码
package struct; // late in first out,LIFO public class MyStack<E> { private Node<E> head = null; public MyStack(){} public MyStack(E element) { Node<E> newNode = new Node<E>(element); head = newNode; } privateclass Node<E> { E element; Node<E> next; public Node(E element) { this.element = element; } } //pop out a elementpublic E pop() { Node<E> popOut = head; head=head.next; return popOut.element; } //push a new element into stackpublicvoid push(E element) { Node<E> newNode = new Node<E>(element); if(head!=null) { newNode.next=head; head=newNode; } else { head=newNode; } } //show the first elementpublic E peek() { return head.element; } //empty or notpublicboolean empty() { if(head!=null) returnfalse; elsereturntrue; } publicstaticvoid main(String[] args) { //about String MyStack<String> stack1 = new MyStack<String>(); stack1.push("sss"); stack1.push("dddd"); stack1.push("dsds"); System.out.println("begin"); while(stack1.empty()==false) { System.out.print(stack1.pop()+" "); } System.out.println(); System.out.println("end"); //about Integer MyStack<Integer> stack2 = new MyStack<Integer>(); stack2.push(212); stack2.push(545); stack2.push(54643); stack2.push(000); System.out.println("begin"); while(stack2.empty()==false) { System.out.print(stack2.pop()+" "); } System.out.println(); System.out.println("end"); //no matter of the type MyStack stack3 = new MyStack(); stack3.push(212); stack3.push("sdad"); stack3.push(54643.787f); stack3.push(0.98989); System.out.println("begin"); while(stack3.empty()==false) { System.out.print(stack3.pop()+" "); } System.out.println(); System.out.println("end"); //LIFO MyStack<String> stack4 = new MyStack<String>("first"); stack4.push("second"); stack4.push("third"); stack4.push("forth"); System.out.println("begin"); while(stack4.empty()==false) { System.out.print(stack4.pop()+" "); } System.out.println(); System.out.println("end"); } }
在写这个数据结构的过程中,也稍微复习了一下泛型。然后注意到,其实泛型类型是不能用基本类型的,至少要用基本类型的相应包装类。
泛型类型必须是引用类型。不能用像int、double或char这样的基本类型来替换泛型类型。而应该使用对应的Integer、Double或Character来代替。
————Java语言程序设计 进阶篇(原书第8版)
原文:http://www.cnblogs.com/kumu/p/6714994.html
内容总结
以上是互联网集市为您收集整理的Java-数据结构练习全部内容,希望文章能够帮你解决Java-数据结构练习所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。