达到列表变量的值

Reaching for the values of variables of a list

本文关键字:变量 列表      更新时间:2023-10-16

我需要在链表中添加变量的值。我可以达到某个值,但不能将 2 个值添加到总和中。

假设我有两个科目,第一个有20分,第二个有10分。

struct subject {
    int points;
    subject *next;
    subject();
};
// testCounter = 2
void list::test(int points, int testCounter) {
    subject *test = new subject;
    int sum = 0, counter = 0;
    for (int i = 1;i <= testCounter;i++,counter++) {
        sum += points;      // maybe "test->points = points" ??
        test = test->next;
    }
    cout << "nCounter: " << couter;   // here I get 2 like I want. 
    cout << "nSum: " << sum; 
}

在"总和"中,我得到 10,第二个值,而不是像我两个值相加后得到的 30。为什么?

是什么: 积分请注意,您永远不会更改它,因此假设您在"test"列表中有 2 个元素所以

void list::test(int points, int testCounter) {
    subject *test = new subject;//

^在这里,您创建一个完整的新列表,该列表有 1 个元素,并且它的点值从未初始化过

    int sum = 0, counter = 0;
    for (int i = 1;i <= testCounter;i++,counter++) { 

^处理列表时,请始终检查您是否没有访问空"链"

        sum += points;      // maybe "test->points = points" ?? <- 

更像是总和 += 测试>点;

        test = test->next;
    }
    cout << "nCounter: " << couter;   // here I get 2 like I want. 
    cout << "nSum: " << sum; 
}

所以让我们重写它:

a) 假设:

subject *mylist = new subject; // you can make a constructor for an element instead of what i'm going to do
mylist->points  = 10;
mylist->next = new subject;
(mylist->next)->points = 20;
(mylist->next)->next = nullptr; //super important remember in c and c++ there's no default value it contain garbage - meaning illegal address

^现在我们基本上将mylist作为两个元素的列表,以最后一个元素结束因此,我们将编写一个函数来获取列表并获取要打印的元素数的 x

void printXElementsInList(const subject *mylist, int x)
{
   int counter = 0, sum = 0;
   while (mylist && counter < x) /*try to make the same thing without mylist and 3 
  instead with the same list, without inserting nullptr it will print 2 and 30 
 cause that's what we have otherwise it will throw an exception!*/
   {
      sum += mylist->points;  //here i'm accessing the points value inside the each chain in the linked list
      mylist = mylist->next; 
      ++counter;
   }
   cout << "counter: " << counter << "nsum: " << sum << endl;
}

请注意,我创建列表的方式非常丑陋,但该功能对您的问题很重要,而不是如何正确创建列表:)HF,希望现在一切都更清楚了