【问题标题】:a loop that prints all the items (no matter how long the chain is) *pointers打印所有项目的循环(无论链有多长)*指针
【发布时间】:2018-02-20 05:23:51
【问题描述】:

以下是基本代码,我想知道编写关于如何显示指针数组中的内容/数据的循环的基本方法是什么。顶部是一个所有内容都公开的类。声明一个字符串数据,后跟一个称为 next 的指针数组。在主函数中,我声明了几个节点并为其分配内存,然后是一个字符串。 A、B 和 C。在代码的最后,我将指向每个数据的指针和最后一个 C 连接到 NULL。最后,我在编写或掌握有关如何编写循环以显示其内容的概念时遇到了一些麻烦,即Node1,Node2,Node3 ...最好是一个无论大小都可以显示所有内容的循环.

#include <iostream>
using namespace std;

class node
{
public:
    string data;
    node * next;
};


int main()
{

    node * A;
    A = new node;
    (*A).data = "node1";


    node * B;
    B = new node;
    (*B).data = "node2";

    node * C;
    C = new node;
    (*C).data = "node3";

    (*A).next = B;
    (*B).next = C;
    (*C).next = NULL;

    for(int i=0; *(next) != NULL; i++)
    {
        cout << *next[i[] << endl;
    }


    system("pause");
    return 0;
}

【问题讨论】:

  • 这不会编译。尝试将其设为minimal reproducible example,我很确定您将拥有解决问题的关键。
  • 由于for循环而无法编译。这就是这篇文章的原因。
  • 我会坚持@Sunil 分辨率。这里不需要 for 循环,由于您处理的数据类型,一段时间更合适。

标签: c++ arrays pointers


【解决方案1】:

使用在节点开始时初始化的临时指针并使用while 循环。

Node* tmp = A;
while (tmp) {   // same as (tmp != NULL)
  cout << tmp->data << endl;
  tmp = tmp->next;   // down the rabbit hole
}

另外,你可以用赋值折叠变量的声明。

Node* A = new Node;

【讨论】:

    【解决方案2】:

    1.) 删除 for 循环

    printList(A);
    
    void printList(node *first)
    {
       node *first = A;
       while(first)
       {
       cout<<first->data<<endl;
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 2020-02-10
      • 2017-08-16
      • 2020-07-22
      • 2022-11-17
      相关资源
      最近更新 更多