我正在编写一个简单的程序,它是关于在 C# 中使用链表的多项式。我遇到的问题是,每当它在 for 循环中创建一个新结构(节点)时,它都会给它与前一个节点相同的地址。我该如何解决?这是我的结构:
struct poly { public int coef; public int pow; public poly* link;} ;
这就是问题发生的地方:
for (; i < this.textBox1.Text.Length; i++)
{
q = new poly();
...
p->link = &q;
}
但&q
保持不变!
更新:
为了更清楚地说明,这里是完整的代码:
namespace PolyListProject
{
unsafe public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
struct poly { public int coef; public int pow; public poly* link;} ;
poly *start ;
poly *p;
private void button1_Click(object sender, EventArgs e)
{
string holder = "";
poly q = new poly();
start = &q;
int i = 0;
while (this.textBox1.Text[i] != ',')
{
holder += this.textBox1.Text[i];
i++;
}
q.coef = int.Parse(holder);
i++;
holder = "";
while (this.textBox1.Text[i] != ';')
{
holder += this.textBox1.Text[i];
i++;
}
q.pow = int.Parse(holder);
holder = "";
p = start;
//creation of the first node finished!
i++;
for (; i < this.textBox1.Text.Length; i++)
{
q = new poly();
while (this.textBox1.Text[i] != ',')
{
holder += this.textBox1.Text[i];
i++;
}
q.coef = int.Parse(holder);
holder = "";
i++;
while (this.textBox1.Text[i] != ';'&& i < this.textBox1.Text.Length-1)
{
holder += this.textBox1.Text[i];
if (i < this.textBox1.Text.Length-1)
i++;
}
q.pow = int.Parse(holder);
holder = "";
p->link = q;
}
p->link = null;
}
}
}
我们的教授要求我们用 C 来做,但我们决定用 C# 来做,但给它一个 C 的外观,因为没有人真正使用 C。