队列:队列末尾的boolean put()对象

时间:2018-12-03 10:57:32

标签: java boolean queue nodes

前段时间我在类中编写了代码(1),这是否意味着对象newObj将放置在队列的开头?如果是,(2)是否将对象newObj放置在末尾并指向最后一个节点的位置?

(1)

public boolean put(AnyClass newObj) {
    if (currNodes == maxNodes) {
        return false;
    } else {
        Node newNode = new Node(newObj);

        if (front == null) {
            front = newNode;
        } else {
            rear.next = newNode;
        }

        rear = newNode;
        currNodes++;

        return true;
    }
}

(2)

public boolean put(AnyClass newObj) {
    if (currNodes == maxNodes) {
        return false;
    } else {
        Node newNode = new Node(newObj);

        if (rear == null) {
            rear = newNode;
        } else {
            front.next = newNode;
        }


        front = newNode;
        currNodes++;

        return true;
    }
}

1 个答案:

答案 0 :(得分:0)

Your first code places a new element to the end (rear) of the queue. However, the second code doesn't place a new element to the start (front) and it does a completely different thing because this is a single linked list and you don't have a pointer to the back.(I assume that the next pointers of your linked list are directed from front to rear).

If you draw the linked list on a paper and execute the code line by line, you will understand well.