这是翻转链表的一段程序,明明这段程序中函数的return一定会是循环体中的if语句中结束,然后return,根本都不会执行到正常结束循环,然后执行最后一句return语句。但是似乎最后一句return语句还必须加上,。java为什么要设计成这样?
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return null;
ListNode pre = null;
ListNode curr = head;
while(curr != null){
if (curr.next == null){
curr.next = pre;
return curr;
}
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return curr;
}
}
但是下面这段程序却又不用最后加上一句return语句,而且加上最后一句return反而会报错。说是最后一句语句无法执行不到。java的编译器倒是怎么搞的。
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return null;
ListNode pre = null;
ListNode curr = head;
while(true){
if (curr.next == null){
curr.next = pre;
return curr;
}
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return curr; // 加上最后这句话会报错。
}
}
The reason is very simple, because for the first one: the value of curr may be null, because when initializing ListNode, the memory application may not be successful due to various problems (for example, there is no available memory at this time ), so this while may exit, and may be executed later, so there must be return
And the second one: You have clearly indicated that the value in while is true, so it is obviously impossible to execute to the end
Another explanation is that this is related to your compiler. while (true) is the range that the compiler can detect, but while (curr != null) cannot be detected at the compilation stage, that is, compilation The processor cannot determine whether it will be executed to the end. .