*TLDR;因为在 while 循环结束时,'head' 指向 null,而不是反向列表。
--
让我们通过一个例子来理解你的代码:
列表:3 -> 6 -> 9 -> 空
头指向3。
// 1
Node<T> prev = null;
while(head != null) // true
Node<T> next = head.next; // next -> 6, as head.next points to Node with element 6
head.next = prev; // head->next = null, earlier it pointed to Node with element 6, prev is null
prev = head;
head = next;
当前状态:
null <- 3 6 -> 9 -> null
Now, prev points to 3, head points to 6.
// 2
while(head != null) // true
Node<T> next = head.next; // next -> 9, as head.next points to Node with element 9
head.next = prev; // head->next =3, earlier it pointed to Node with element 9, prev is 3
prev = head;
head = next;
当前状态:
null <- 3 <- 6 9 -> null
Now, prev points to 6, head points to 9.
// 3
while(head != null) // true
Node<T> next = head.next; // next -> null, as head.next points to null
head.next = prev; // head->next =6, earlier it pointed to null, prev is 6
prev = head;
head = next;
当前状态:
null <- 3 <- 6 <- 9
Now, prev points to 9, head points to null.
// 4
while(head != null) // false
Now, head points to null and you need to return reversed linked list.
head = prev; // prev points to the node with element 9.
// null <- 3 <- 6 <- 9 <- prev (or head) as head and prev are equal.
return prev; // will return the reversed linked list.
return head; // will return the reversed linked list as both prev and head are equal.