Implement Queue by Linked List

题目:

Implement a Queue by linked list. Support the following basic methods:

enqueue(item). Put a new item in the queue.
dequeue(). Move the first item out of the queue, return it.

分析:

做法跟前面的implement by interface基本一样

解法:

class ListNode {
    public int val;
    public ListNode next;
    public ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

public class Queue {
    public ListNode first, last;
    public Queue() {
        // do initialize if necessary
    }

    public void enqueue(int item) {
        // Write your code here
        if (first == null || last == null) {
            last = new ListNode(item);
            first = last;
        } else {
            last.next = new ListNode(item);
            last = last.next;
        }
    }

    public int dequeue() {
        // Write your code here
        int res = -1;
        if (first == null || last == null) {

        } else if (first == last) {
            res = first.val;
            first = null;
            last = null;
        } else {
            res = first.val;
            ListNode temp = first.next;
            first.next = null;
            first = temp;
        }
        return res;
    }
}

results matching ""

    No results matching ""