将值存储在链表中的结构中

Storing values in a struct in a linked list

本文关键字:结构 链表 存储      更新时间:2023-10-16

我想知道如何将值存储到作为结构链表一部分的结构中。我有:

struct polynomial
{
    polynomial(string newCoefficient, string newPower, polynomial *nextPtr);
    string coefficient;
    string power;
    polynomial *next; 
};
class linkedList
{
public:
    void createList();
private:
    polynomial *head;
};

对于这个赋值,我们需要在收集输入值时进行一些解析。例如,我们要输入两个用空格分隔的数字(例如7 9或10 8)。因此,在void createList()中,我想使用字符串读取一行,将其转换为一个char数组以去掉值,然后将该值存储到链表中每个节点的polynomial.coefficient和polynomial.power中。

或者,我在搜索一些信息,我想也许我可以输入两个int值,然后使用字符串流将它们转换为字符串,并将它们存储为系数和幂。

不管怎样,你能帮我介绍一下将值存储到链接列表结构中的概念吗?

编辑:我添加了重载构造函数:

polynomial:: polynomial ( string newCoefficient, string newPower, polynomial *nextPtr )
{
    coefficient = newCoefficient;
    power = newPower; 
    next = nextPtr; 
};

您将C风格练习与C++练习混合在一起。

在C++中,通常将数据与容器分离。看看std::list是如何工作的。

即使你不想进入模板,你仍然可以这样做:

struct polynomial {
   string coefficient;
   string power;
};
struct listnode {
   polynomial data;
   listnode *next;
};

如果你真的想拥有head的概念,你可以保留一个"假头",在那里你可以存储一个什么都没有的listnode

或者,如果你真的想在polynomial中使用next指针,并且你想在不破坏指针的情况下复制现有元素,只需制作一个setter函数:

void polynomial::set( const string& inCoeff, const string & inPower );

我测试了以下代码,这些代码可能会帮助您:

struct Polynomial {
        string coefficient;
        string power;
        Polynomial* next;
        Polynomial(const string& coeff, const string& pow) : coefficient(coeff), power(pow), next(NULL) {}
};
// linked-list of Polynomials
struct LinkedList {
    Polynomial* head;
    LinkedList() : head(NULL) {}
    // add to end of list        
    void add(const string& coeff, const string& pow) {
        if(head == NULL)
            head = new Polynomial(coeff, pow);
        else {
            Polynomial* n;
            for(n = head; n->next != NULL; n = n->next);
            n->next = new Polynomial(coeff, pow);
        }
    }
    // check if results are correct
    void print() {
        for(Polynomial* n = head; n != NULL; n = n->next)
            cout << n->coefficient << " " << n->power << endl;
    }
};
// somewhere in main()
LinkedList ll;
...
// read input values
ll.add(coeff1, pow1);
ll.add(coeff2, pow2);
ll.add(coeff3, pow3);
// check results
ll.print();

请注意,多项式结构成员不需要是字符串。相反,您可以解析输入并将cofficient存储为float,将power存储为int(所有多项式指数都是整数)。