当循环正在执行我不明白的代码时

While loop is executing code I don't understand

本文关键字:明白 代码 循环 执行      更新时间:2023-10-16

谁能解释一下这个程序是如何工作的?我不知道"while"循环中发生了什么

struct L {
int d;
L *p;}
L* l = new L;
l->d = 3;
l->p = new L;
l->p->d = 5; //Is this a substructure?
l->p->p = l;
while(l->d < 7) {
cout << l->d++ << ' ';
l = l->p; // ??
}
// L is a data structure also known as a linked list. It has:
struct L
{
int d; // a value
L *p;  // a pointer to the next element
}
// it creates the first element of the linked list, and assigns it a value of 3
L* l = new L;
l->d = 3;
// then makes it point to a new element, with value 5
l->p = new L;
l->p->d = 5;
// the new element's pointer to the next element is then set to be 
// the first item in the list, hence creating a circular list of 2 elements
// .->| 3 |-->| 5 | -.
// '-----------------'
l->p->p = l;
// then it loops through the list, printing the value of the current element 
// and increasing it to 1 every time, and stopping when the value of the current 
// element is 7 or more
while(l->d < 7) {
cout << l->d++ << ' '; // prints the value of the current element and increases it
l = l->p; // moves to the next node
}

这里有一篇非常好的文章,可以帮助你理解什么是链表以及如何正确使用它:https://www.learn-c.org/en/Linked_lists

我希望这已经足够清楚了!