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

利用尾插入法建立单向链表,开始结点充当队列的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;
    }
}

 

posted @ 2015-10-05 19:12  lasclocker  阅读(351)  评论(0编辑  收藏  举报