zoukankan      html  css  js  c++  java
  • Use LinkedList to implement Queue

     1 /*             H            tail
     2          (last in) 1->2->3->4 (1st in)
     3                       o/H
     4                             first-out
     5 
     6      */
     7 public class UseLinkedListImplementQueue {
     8     private ListNode head ;
     9     private ListNode tail ;
    10     private int length;
    11 
    12     public UseLinkedListImplementQueue() {
    13         head = null ;
    14         tail = null ;
    15         length = 0;
    16     }
    17 
    18     public void offer(int val){
    19         ListNode node = new ListNode(val) ;
    20         node.next = head ;
    21         head = node ;
    22         length++;
    23         syncHeadAndTail();
    24     }
    25     // 1->2->3->4   to 1->2->3
    26     public Integer poll(){
    27         if (tail == null)  return null;
    28         int value = tail.val ;
    29         ListNode curr = head ;
    30         while (curr != null && curr.next != tail){
    31             curr = curr.next ;
    32         }
    33         //now curr.next -> tail
    34         curr.next = null ;
    35         //move tail to curr
    36         tail = curr ;
    37         length-- ;
    38         syncHeadAndTail();
    39         return value ;
    40     }
    41 
    42     public Integer peek(){
    43         if (tail == null) return null ;
    44         return tail.val ;
    45     }
    46 
    47     public boolean isEmpty(){
    48         return this.length <= 0 ;
    49     }
    50 
    51     public int getSize(){
    52         return this.length ;
    53     }
    54 
    55     private void syncHeadAndTail(){
    56      if (this.length == 0){
    57          head = null ;
    58          tail = null ;
    59      }
    60      if (this.length == 1){
    61          tail = head ;
    62      }
    63     }
    64 
    65     public static void main(String[] args) {
    66         UseLinkedListImplementQueue queue = new UseLinkedListImplementQueue() ;
    67         queue.offer(1);
    68         queue.offer(2);
    69         System.out.println(queue.poll());
    70         queue.offer(3);
    71         queue.offer(4);
    72         System.out.println(queue.poll());
    73         System.out.println(queue.poll());
    74 
    75     }

  • 相关阅读:
    yii主题
    aptana studio 使用技巧整理
    big database url
    yii表单输入元素
    下载,和scp上传问题
    对缓存的思考——提高命中率
    php用户名密码
    openx -书表添加字段
    搜索
    python——常用模块2
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8648445.html
Copyright © 2011-2022 走看看