首页 > 其他 > 详细

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

时间:2015-10-05 19:32:04      阅读:290      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!