Use LinkedList to implement Queue

本文介绍了一种使用链表来实现队列数据结构的方法。通过定义节点类和队列类,实现了队列的基本操作,如入队、出队、查看队首元素等。文章通过具体的Java代码展示了如何进行链表与队列之间的转换。
 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     }

 

 

转载于:https://www.cnblogs.com/davidnyc/p/8648445.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值