带有指针的动态堆栈结构

dynamic stack structures with pointers

本文关键字:堆栈 结构 动态 指针      更新时间:2023-10-16

我正在构建一个动态堆栈,它需要一个带有指向数组的指针的结构。

class studentstack
{
  private:
          struct StackNode
          {
                  int ID;
                  string Name;
                  string Address;
                  StackNode * next; // pointer to the next node
                  double * scores; // pointer to the arry of scores
          };
当我

的主文件中我试图用双精度填充数组然后将其传递给一个函数时,当我什么都不做时,似乎传递正确。 正确的方法是什么?

int main()
{
    studentstack s;
    string name;
    int id;
    string address;
    double score;


    for(int x =0; x<20; x++)
    {
        cout << "nNew Student Name: ";
        cin >> name;
        cout << "nID: ";
        cin >> id;
        cout << "nAddress: ";
        cin >> address;
        double scoresArr[10];
        for(int z=0; z<10; z++)
        {
                cout << "nStudent Score " << z+1 << ": ";
                cin >> score;
                scoresArr[z] = score;
        }
        s.push(name, id, address, scoresArr);

推:

void studentstack::push(string name, int id, string address, double scoresArr)
{
     StackNode *newStudent; // To point to the new Student
     newStudent = new StackNode;
     newStudent-> ID = id;
     newStudent-> Name = name;
     newStudent-> Address = address;
     newStudent-> scores = scoresArr;
     // If there are no nodes in the stack
     if (isEmpty())
     {
        top = newStudent;
        newStudent->next= NULL;
     }
     else // or add before top
     {
          newStudent->next = top;
          top = newStudent;
     }
}     

技术问题在于您尚未显示的代码(当我编写本文时),即push代码。

但是,有一个简单的解决方案,无论您的push如何搞砸事情,它都会起作用。

也就是说,使用 std::vector 而不是动态分配的原始数组。

或者,只需在每个节点中使用固定大小的原始数组。

就此而言,std::list会比DIY链表更好,但大概这个练习的重点在于熟悉链表结构。对每个节点中的阵列使用 std::vector 不会干扰该目标。但请记住,在现代C++无论问题是什么,自己创建链表都很少是一个好的解决方案 - 相反,使用标准库容器类和/或来自第三方库的容器类。