使用while循环创建链接列表

时间:2014-09-29 19:38:18

标签: c++ while-loop linked-list

我需要创建一个类成员(Binary)的链表,我遇到了无限循环问题。 Binary类只包含degree(int)和下一个节点指针。 在二进制类中,二进制链表的实现正在set_bit方法中执行。 set_bit方法有两个整数,它们是1/0 int(bit)和int int。但此时不需要这个位。

set_bit方法如下:

void Binary::set_bit(int b, int d){
    BinaryNode* current = firstTerm;
    BinaryNode* toSet;

    if (current == NULL) {

        firstTerm = new BinaryNode(d, NULL);
        current = firstTerm;

        cout << "\nd: " << d << " <--> current degree: " << current->degree << endl;
        system("pause");

    } else {
        while (current != NULL){
            firstTerm = new BinaryNode(d, current);
            cout << "\nd: " << d << " <--> current degree: " << current->degree << endl;
            cout << "first term: " << firstTerm->degree << endl;
            system("pause");
        }
    }
}
在main.cpp文件上的

,我试图设置以下位:

b1.set_bit(1, 2);
b1.set_bit(1, 5);
b1.set_bit(1, 0);
b1.set_bit(0, 2);

该方法设置第一位(2),然后到达下一个(5),然后开始尝试设置该位的无限循环。 我在哪里错了? 我已经向我的实验室指导员寻求帮助,他向我提供了以下代码: 为什么实验室指导员的代码也不起作用?

void Binary ::set_bit( int b , int d ){
  BinaryNode * current = firstTerm;
  if (current == NULL ){
    firstTerm = new BinaryNode(d,NULL); // Corrected Line
  }
  while (current != NULL ){
    firstTerm = new BinaryNode(d,firstTerm); // Corrected Line 
  }
}

由于

1 个答案:

答案 0 :(得分:0)

当然你最终会得到无限循环,因为当你尝试插入第二个节点时,current != NULL总是为真,这意味着调用else部分。不幸的是,里面有一个while loop,其条件总是如此。