• 用非顺序映像实现队列


     1 package myqueue;
     2 
     3 import mylinkedlist.MyLinkedList;
     4 
     5 import java.util.NoSuchElementException;
     6 
     7 public class myQueue <E>{
     8     private Node head;
     9     private Node end;
    10     private int size;
    11 
    12     private static class Node<E>{
    13         public Node next;
    14         public Node prev;
    15         E val;
    16         public Node(E val){
    17             this.val = val;
    18         }
    19         public Node(Node prev,E val,Node next){
    20             this.val = val;
    21             this.next = next;
    22             this.prev = prev;
    23         }
    24     }
    25 
    26     public myQueue(){
    27         head = new Node(null);
    28         end = new Node(null);
    29         head.next = end;
    30         end.prev = head;
    31 
    32     }
    33     public void enque(E e){
    34         Node nodeToEnque = new Node(end.prev,e,end);
    35         end.prev.next = nodeToEnque;
    36         end.prev = nodeToEnque;
    37         size++;
    38     }
    39     public E deque(){
    40         //先判断是否队空
    41         if(isEmpty()){
    42             throw new NoSuchElementException();
    43         }
    44         Node nodeToRemove = head.next;
    45         head.next = head.next.next;
    46         nodeToRemove.next.prev = head;
    47         size--;
    48         return (E)nodeToRemove.val;
    49 
    50     }
    51 
    52     public boolean isEmpty() {
    53         return size==0;
    54     }
    55     public int size(){
    56         return size;
    57     }
    58     public E peek(){
    59         return (E)head.next.val;
    60     }
    61     public String toString(){
    62         StringBuilder sb = new StringBuilder("[");
    63         Node x =head.next;
    64         while(x!=end){
    65             sb.append(x.val).append(", ");
    66             x =x.next;
    67         }
    68         if(size !=0) sb.delete(sb.length()-2,sb.length());
    69         return sb.append("]").toString();
    70     }
    71 
    72 }
     1 package myqueue;
     2 
     3 public class TestMyQueue {
     4     public static void main(String args[]){
     5         myQueue<Integer> que = new myQueue();
     6         System.out.println("队列空吗?"+que.isEmpty());
     7         que.enque(1);
     8         que.enque(2);
     9         que.enque(3);
    10         que.enque(4);
    11         System.out.println(que.toString()+",长度位:"+que.size());
    12         System.out.println("出队:"+que.deque());
    13         System.out.println("队列空吗?"+que.isEmpty());
    14 
    15 
    16     }
    17 }
  • 相关阅读:
    用prototype属性来模拟一下类的继承
    Ajax 教程:Ajax 入门简介
    Ajax工作原理
    最新的Ajax教程和技术(上篇)
    javascript面向对象技术基础
    浏览器对象模型
    jQuery (选择器,属性,筛选,文档处理)
    shell(一)
    ntpntpdate时间同步
    centos7新系统安装
  • 原文地址:https://www.cnblogs.com/debug-the-heart/p/13334255.html
Copyright © 2020-2023  润新知