码迷,mamicode.com
首页 > 其他好文 > 详细

链式队列(单向列表实现)

时间:2015-10-05 19:33:17      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

利用单向链表,开始结点充当队列的head,末尾结点充当队列的tail,并考虑下溢出。

class ListNode {
    ListNode next;
    int val;
    public ListNode(int x) {
        val = x;
    }
}
public class Queue {
    private ListNode head, tail;
    public Queue() {
        head = null; tail = null;
    }
    public void enqueue(int x) {
        if(isEmpty()) {
            tail = new ListNode(x);
            head = tail;
        } else {
            ListNode tmp = new ListNode(x);
            tail.next = tmp;
            tail = tmp;
        }
    }
    public int dequeue() throws Exception {
        if(isEmpty()) throw new Exception("underflow");
        else {
            int tmp = head.val;
            head = head.next;
            return tmp;
        }
    }
    public int peek() throws Exception {
        if(isEmpty()) throw new Exception("underflow");
        else return head.val;
    }
    public boolean isEmpty() {
        return head == null;
    }
    public void clear() {
        head = null;
    }
}

 

链式队列(单向列表实现)

标签:

原文地址:http://www.cnblogs.com/lasclocker/p/4856132.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!