奇怪的 while 循环与分配操作C++



我在leetcode解决方案中看到过以下代码片段。它计算链表中元素的数量。while 语句只有一个赋值操作。谁能解释一下这是如何工作的。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct ListNode * temp = head;
int num = 1;
while(temp = temp->next){
num++;
}
  1. temp->next的值分配给temp
  2. 评估while(temp)(如temp != NULL(
  3. 在执行循环体的情况下

注意:如果head为 NULL,您的程序将面临运行时错误

最新更新