虽然循环正在执行我不明白的代码

时间:2019-10-12 12:54:13

标签: c++ pointers struct

谁能解释一下该程序的工作原理?我不知道“ while”循环中发生了什么

jQuery

1 个答案:

答案 0 :(得分:1)

// 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

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