打印链接列表中的元素

问题描述 投票:-6回答:3

如果我有一个int的链接列表,我如何迭代/遍历链表,以便我可以用C ++中的cout打印每个元素?

c++ algorithm
3个回答
0
投票

据推测,您的链表具有典型的链表操作。这包括获取引用第一个元素的迭代器,递增迭代器以引用下一个元素,检查迭代器是否已经从列表末尾运行,依此类推。算法是:

  1. 设置迭代器以引用链表中的第一个元素。
  2. 如果迭代器已经运行链表的末尾,请停止。
  3. 打印迭代器引用的元素。
  4. 增加迭代器。
  5. 转到第2步。

如果您不知道如何执行这些特定步骤,那么您不知道如何使用您拥有的特定链接类。为了帮助您,我们需要查看其代码(如果它是现成的类,则需要查看其文档的链接)。

典型的C ++实现看起来像这样:

void LinkedList::print(ostream& stream) const
{
      LinkedListElement* ptr = head; // this is my step 1
      while (ptr != NULL)            // this is my step 2
      {
           stream << *ptr;           // this is my step 3
           ptr = ptr->getNext();     // this is my step 4
      } // step 5 happens here because this is a loop
}

0
投票

你可以用这个:

void print(node* n) {
  cout << n -> value << endl;
  if(n -> next) print(n -> next);
}

并称之为:

int main() {
  linked_list l;
  ...
  print(l -> head);
  return 0;
}

0
投票

希望这可以帮助!

struct Node
    {
         int data;
         struct Node *next;
    }

void Print(Node *head)
{
    Node *a =head;
    while(a!=NULL){
        cout<<a->data<<endl;
        a = a->next;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.