Jazzertron
Jazzertron

Reputation: 63

How could I re-write this java method with a while loop?

It's supposed to take the last element out of a pseudo-LinkedList. The instructions suggested using a while loop to find the next-to-last element.

public String removeFromEnd() {
    String removed = null;
    if (head == null) {
        return removed;
    } else if (head.getNext() == null) {
        removed = head.getName();
        head = null;
    } else if (head.getNext().getNext() == null) {
        removed = head.getNext().getName();
        head.setNext(null);
    }
    return removed;
}

Past attempts usually look similar to this:

public String removeFromEnd() {
    String removed = null;
    while (head.getNext().getNext() == null){
        removed = head.getNext().getName();
        head.setNext(null);
    }
    if (head.getNext() == null){
        removed = head.getName();
                    head = null;
    }
    return removed;
}

Upvotes: 2

Views: 704

Answers (3)

Mr.Powers
Mr.Powers

Reputation: 163

// Java Code
public String removeFromEnd() {
String removed = null;
Node prev = null;
Node node = head;
        while(node != null && node.getNext() != null)
        {
            prev = node;
            node = node.getNext();
        }
        //the while loop should move the node to the end of the list
        if(node != null)
        {
        removed = node.getName();
        node = prev;
        node.getNext().removeNode();
        node.setNext(null);
        }
        return removed;
}

Upvotes: 1

Kevin
Kevin

Reputation: 25269

  Node node = head;
  Node prev = null;
  while (node != null && node.getNext() != null) {
      prev = node;
      node = node.getNext();
  }

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198033

In your attempt code...

while (head.getNext().getNext() == null){
    removed = head.getNext().getName();
    head.setNext(null);
}

You'll only enter this loop when head is already the second-to-last element. You want to loop until head is the second-to-last element. Does that help at all?

Upvotes: 1

Related Questions