这个for loop如何翻译成英文?

时间:2019-03-09 01:12:54

标签: java for-loop linked-list

所以基本上我是从教授那儿得到的代码,但是我从未见过有人写过这样的for循环。我什至不知道如何开始阅读?谁能告诉我您将如何首先用英语阅读,然后在for循环中使用它的最佳方法是什么? 也认为不需要此信息,但以防万一,我们正在使用Java处理链表。

预先感谢

    public void delete(Object el) {    // find and remove el;  
    if (head != null)              // if non-empty list;
         if (el.equals(head.info)) // if head needs to be removed;
              head = head.next;
         else {
              SLLNode pred = head, tmp = head.next;
              for ( ; tmp != null && !(tmp.info.equals(el));
                      pred = pred.next, tmp = tmp.next);
              if (tmp != null)     // if found
                    pred.next = tmp.next;
         }
}

3 个答案:

答案 0 :(得分:2)

for(x;y;z) { ...; }

等同于

x;
while(y) {
  ...;
  z;
}

所以

  for ( ; tmp != null && !(tmp.info.equals(el));
          pred = pred.next, tmp = tmp.next);

等效于:

while(tmp != null && !(tmp.info.equals(el))) {
  pred = pred.next, tmp = tmp.next;
}

用英语,就像

  

直到找到要查找的元素或列表的末尾:将前任元素和当前元素更新为各自的下一个元素

答案 1 :(得分:1)

Java for loop的格式为:

for (initialization; termination; increment) {
    statement(s);
}

您的示例代码是:

for ( ; tmp != null && !(tmp.info.equals(el));
        pred = pred.next, tmp = tmp.next);

如果我们将其分解,您可以在此处看到

  • 不是初始化步骤
  • 终止的两个部分
  • increment 步骤中的
  • 两个(逗号分隔)语句

粗略的英语:

  • 保持循环,直到tmpnulltmp匹配要删除的元素,即。遍历列表,直到到达末尾或找到匹配项
  • 每次循环,通过将它们指向下一项 crement predtmp

答案 2 :(得分:0)

for循环由四个部分组成:初始化表达式终止表达式增量表达式,和 body

(还有一个 for-each 样式循环,具有不同的语法,但这不是我们在这里谈论的内容。)

因此,可以将其解析:

  • 初始化表达式为空(第一个;之前没有)
  • 终止表达式tmp != null && !(tmp.info.equals(el)
  • 增量表达式pred = pred.next, tmp = tmp.next
  • body 也是空的(在)表达式的for结束后,下一条语句只是;

简而言之:

  

只要tmp不是null,但是tmp.info不是我们想要的元素el,请继续将predtmp移动到指向链接列表中的后继元素。

此循环的终止条件是tmpnull(如果el根本不是列表的元素),或者pred指向节点 before el作为值的节点,而tmp指向以el作为值的节点。

请注意,此代码以非常简洁的样式编写。这种样式在20年前的低级代码中很常见;如今,当我看到这样的代码时,让我觉得它是由旧计时器编写的。

我可能会写同样的方法:

public void delete(Object item) {
    if (head == null) {
        // The list is empty; we have no work to do.
        return;
    }
    if (head.info.equals(item)) {
        // We're deleting the head of the list; just update our head reference.
        head = head.next;
        return;
    }
    SLLNode previous = head;
    SLLNode current = head.next;
    while (current != null) {
        if (current.info.equals(item)) {
            // Update the list to skip the current node, then we're done.
            previous.next = current.next;
            return;
        }
        // Move to the next node in the list.
        previous = current;
        current = current.next;
    }
    // If we reached this point, the item was not found in this list.
    // There's nothing to do, so we're done anyway.
}
相关问题