zoukankan      html  css  js  c++  java
  • Java-数据结构之栈练习

    栈(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; } private class Node<E> { E element; Node<E> next; public Node(E element) { this.element = element; } } //弹出一个元素 public E pop() { Node<E> popOut = head; head=head.next; return popOut.element; } //压入一个元素 public void push(E element) { Node<E> newNode = new Node<E>(element); if(head!=null) { newNode.next=head; head=newNode; } else { head=newNode; } } //展示第一个元素 public E peek() { return head.element; } //是否为空 public boolean empty() { if(head!=null) return false; else return true; } public static void main(String[] args) { //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"); //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"); //多种类型 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"); //展示后进先出 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版)

  • 相关阅读:
    Bayesian CTR Prediction for Bing
    Gaussian and Truncated Gaussian
    An Introduction to Variational Methods (5.3)
    An Introduction to Variational Methods (5.2)
    An Introduction to Variational Methods (5.1)
    Variational Bayes
    微软的一篇ctr预估的论文:Web-Scale Bayesian Click-Through Rate Prediction for Sponsored Search Advertising in Microsoft’s Bing Search Engine。
    第五十二课、命令行参数的应用------------------狄泰软件学院
    第五十一课、程序中的配置文件------------------狄泰软件学院
    第五十课、关于对话框(About)------------------狄泰软件学院
  • 原文地址:https://www.cnblogs.com/kumu/p/6714994.html
Copyright © 2011-2022 走看看