zoukankan      html  css  js  c++  java
  • java算法:FIFO队列

    java算法:FIFO队列

    FIFO队列是一个ADT,由两个基本操作构成:插入(放入)一个新项,删除(得到)最早插入的项。

    例1:FIFO队列ADT接口

    Java代码 复制代码
    1. interface intQueue{   
    2.     intQueue(int q);   
    3.     int empty();   
    4.     void put(int q);   
    5.     int get();   
    6. }  

    使用数组或链表,在常数时间内实现FIFO队列ADT的get和put操作。

    例2:FIFO队列的链表实现

    Java代码 复制代码
    1. public class intQueue{   
    2.     private class Node{   
    3.         int item;   
    4.         Node next;   
    5.         Node(int item){   
    6.             this.item = item;    
    7.             next = null;   
    8.         }   
    9.     }   
    10.     private Node head, tail;   
    11.     intQueue(int max){   
    12.         head = null;   
    13.         tail = null;   
    14.     }   
    15.     boolean empty(){   
    16.         return (head == null);   
    17.     }   
    18.     void put(int item){   
    19.         Node t = tail;   
    20.         tail = new Node(item);   
    21.         if(empty()){   
    22.             head = tail;       
    23.         }else{   
    24.             t.next = tail;   
    25.         }   
    26.     }   
    27.     int get(){   
    28.         int v = head.item;   
    29.         Node t = head.next;   
    30.         head = t;   
    31.         return v;   
    32.     }   
    33. }  

    数组要求自始自终都要为预计的最大的项数保留足够的空间,而链表表示使用的空间与数据结构中的元素个数成比例,但要为指针分配额外的空间,并且每个操作都要花分配和释放内存的额外时间。

    例3:FIFO队列的数组实现

    Java代码 复制代码
    1. public class intQueue{   
    2.   
    3.     private int[] q;   
    4.     private int N, head, tail;   
    5.   
    6.     intQueue(int max){   
    7.         q = new int[maxN + 1];   
    8.         head = N;   
    9.         tail = 0;   
    10.     }   
    11.     boolean empty(){   
    12.         return (head%N == tail);   
    13.     }   
    14.     void put(int item){   
    15.         q[tail++] = item;   
    16.         tail = tail%N;   
    17.     }   
    18.     int get(){   
    19.         head = head%N;   
    20.         return q[head++];   
    21.     }   
    22. }  

    拓展:双端队列,删除随机项队列(如果第一项则是FIFO队列,如果最后一项则是栈),或者删除关键字项,自定义项等。

  • 相关阅读:
    给任意多个链表然后要合并成一个
    hdu5967数学找规律+逆元
    poj2125最小点权覆盖+找一个割集
    poj3308 最小点权覆盖
    poj2987 最大闭合权子图基础题
    poj2699 转化为可行性判定问题+二分枚举+最大流
    判断割是否唯一zoj2587
    快排优化
    jvm垃圾收集器
    三次握手与四次挥手
  • 原文地址:https://www.cnblogs.com/wuyida/p/6301150.html
Copyright © 2011-2022 走看看