我怎么能用while循环重写这个java方法?

时间:2012-02-23 18:19:52

标签: java loops while-loop

它应该从伪LinkedList中取出最后一个元素。建议使用while循环来查找倒数第二个元素。

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;
}

过去的尝试通常与此类似:

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;
}

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

// 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;
}

答案 2 :(得分:1)

在您的尝试代码中......

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

head已经是倒数第二个元素时,您才会进入此循环。您想循环直到 head是倒数第二个元素。这有帮助吗?