简体   繁体   中英

POP method linked list

I've implemented a pop method in Java I would use it for delimiter matching, though it leaves one element in the list.

    public int length(){
    Node current = this.head;
    int length = 0;
        while(current != null){
            current = current.getNextNode();
            length += 1;
        }
    return length;
}

public char pop(){
    Node current = this.head;
    Node lastN = this.last;

    for(int i = 0; i < length() - 2; i++){
        current = current.getNextNode();
    }
    current.setNextNode(null);
    this.last = current;

    return lastN.getBracket();
}

How do I pop the first element if length is >= 1?, or any suggestion for improving my code.

Use java.util.LinkedList.

With addFirst() , addLast() , size() , removeFirst() and removeLast() you are covered.

Alternatively, check this delimiter check example for another way.

In you code, you miss the "initial" or "last element" case, which is special. You should check for the case of this.head == this.last ; case where you should return the last element and clean up the list.

Why moving through the list elements in the loop? How about instead of that:

if (this.head != null)
{
    char val = this.head.getBracket();
    this.head = this.head.getNextNode();
}

This snippet will drop the first element and set head to point to the second element. I guess JVM will delete old head . If the list is circular, then also set last to point to the new head.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM