将值存储在链接列表中的结构中
我想知道如何将值存储到结构的链接列表的一部分的结构中。我有:将值存储在链接列表中的结构中
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值,然后使用stringstream将它们转换为字符串,并将它们存储为系数和功率。
无论哪种方式,你能帮我介绍一下将值存储到链接列表结构的概念吗?
编辑:我已经添加了重载的构造函数:
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);
有道理! :) – 2013-02-15 02:18:27
我测试了以下代码可能会帮助你:
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
(所有多项式指数都是整数)。
你试图实际存储一个值的地方在哪里? – 2013-02-14 22:54:54