将值存储在链表中的结构中
Storing values in a struct in a linked list
我想知道如何将值存储到作为结构链表一部分的结构中。我有:
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
(所有多项式指数都是整数)。
相关文章:
- 链表,反向函数,数据结构
- 我对数据结构、双向链表有一些问题
- 使用带有链表的堆栈数据结构将中缀转换为后缀
- 使用链表数据结构打印多项式
- C++:如何做一个链表,结构作为参数传递?
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?
- 如何通过不同的指针使用类的对象访问结构?(链表)(C++)
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 在排序链表中插入结构并将其写入二进制文件
- 具有多个结构的链表
- 使用带有结构结构作为 C++; 元素的单向链表
- 如何从文件读取到动态分配的指向结构的指针链表中?
- 结构内具有更多数据类型的单个链表
- 尝试连接两种不同类型的结构来创建链表
- C++中的数据结构,插入链表中节点的开头
- 自定义链表创建 RtlValidateHeap 错误,其结构具有链表
- 难以理解链表实现(结构部分)?
- 访问链表中的结构(带有指向其子实现的指针列表的树)
- C++排序结构链表
- 修改在其他结构(链表)中定义的结构对象的元素