Implement Queue by Linked List

题目:

mplement 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.

接口:

接口有两个,一个入队,一个出队

分析:

本身用一个dummy和一个curr是不难做的,但是有一个特别triky的地方,就是说当你的dummy->next==curr的时候,很有可能一出队就把curr丢掉了。所以出队要分两种情况讨论,来个if语句:

(1) dummy->next == curr

(2) dummy->next != curr

解法:

class Node {
public:
    int val;
    Node* next;
    Node(int x) : val(x), next(NULL) {}
};

class Queue {
    Node* dummy;
    Node* curr;
public:
    Queue() {
        // do initialize if necessary
        dummy = new Node(-1);
        curr = dummy;
    }

    void enqueue(int item) {
        // Write your code here
        Node* temp = new Node(item);
        curr->next = temp;
        curr = temp;
    }

    int dequeue() {
        // Write your code here
        if (dummy->next == NULL) {
            return -1;
        } 

        if (dummy->next == curr) {
            Node* temp = curr;
            dummy->next = NULL;
            curr = dummy;
            return temp->val;
        } else {
            Node* temp = dummy->next;
            dummy->next = dummy->next->next;
            return temp->val;
        }
    }
};

results matching ""

    No results matching ""