【问题标题】:doubly linked list with for loop c++带有for循环c ++的双向链表
【发布时间】:2023-03-11 06:25:01
【问题描述】:

我刚刚学习了 C++ 中的指针,我的导师告诉我创建一个带有 for 循环的双向链表。然而,我得到的唯一例子是

    Node *n1 = new Node(1);
    Node *n2 = new Node(2);
    Node *n3 = new Node(3);
    Node *n4 = new Node(4);
    Node *n5 = new Node(5);
    DL_List mylist;
    if (mylist.empty())
        mylist.insert(n1, mylist.head);
    mylist.insert(n2, n1);
    mylist.insert(n3, n2);
    mylist.insert(n4, n3);
    mylist.insert(n5, n4);
    mylist.display();

我不知道如何为此设置一个 for 循环,因为我不知道如何在循环中命名它们,也不知道如何连接它们。

【问题讨论】:

  • 你可能想去找你的导师。
  • 你是在问如何循环调用insert()?您可以将Node* 指针存储在一个数组中,然后循环遍历该数组
  • 循环的优点之一是it is scoped。您可以反复使用相同的名称。

标签: c++ for-loop nodes doubly-linked-list


【解决方案1】:

名称、标识符没有任何意义。它们只是占位符。我们使用好名字是因为它使人脑更容易理解变量的用途。电脑不在乎。它会尽快删除名称并用地址、地址偏移量或硬件寄存器替换它。

您不能在同一范围内使用相同的标识符,但循环的范围以循环的结尾结束,然后如果循环需要再次迭代,则重新开始重新创建任何标识符。

循环中发生了什么?显然我们需要创建一个Node 并插入节点,但我们还需要跟踪在哪里插入下一个节点。这导致了教师提供的示例中的一个半错误:

DL_List mylist;
if (mylist.empty()) // list better not be constructed with pre-existing nodes
    mylist.insert(n1, mylist.head); // because this doesn't happen if it isn't empty
mylist.insert(n2, n1); // and where is n1, Hmmm? We might not have added it.

n1 不会在列表中,如果它不在列表中,那么将列表中的 n2 链接到 n1 并不是一个好主意。

我的推销行为略有不同,但至少不是破坏行为。我建议总是在列表的开头插入第一个节点。如果列表中已经有东西,那就这样吧。它被推向列表的末尾。

在这种情况下,您需要一个额外的占位符来跟踪插入的位置,并且该占位符的值需要在循环的迭代之间保持不变。为了让它持续存在,我们在循环之外定义它。

Node * where_to_insert = mylist.head;
for (int count = 1; cows.not_home(); count++)
{
    Node * n = new Node(count);
    mylist.insert(n, where_to_insert);
    where_to_insert = n;
}

上面将循环并添加节点,直到奶牛回家。希望它们能在计数溢出之前返回,但可以通过为循环使用更相关的终止条件来避免这种可能性。

【讨论】:

    【解决方案2】:

    我真的不明白 mylist.insert(a, b) 是做什么的?将节点a插入到位置b?通常,按照您所说的,我们使用如下代码:

    for (size_t i = 0; i < number_of_nodes_you_want_to_insert; ++i) {
        Node *n = new Node(i);
        mylist.insert(n);
    }
    

    【讨论】:

    • 无效插入(节点 *newnode,节点 *pred);它应该是双重链接的。
    • 好的,看user4581301的回答。他/她说得很清楚。
    猜你喜欢
    • 2021-07-05
    • 1970-01-01
    • 2013-11-15
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 2014-12-09
    • 2020-12-03
    相关资源
    最近更新 更多