如果我有一个int的链接列表,我如何迭代/遍历链表,以便我可以用C ++中的cout打印每个元素?
据推测,您的链表具有典型的链表操作。这包括获取引用第一个元素的迭代器,递增迭代器以引用下一个元素,检查迭代器是否已经从列表末尾运行,依此类推。算法是:
如果您不知道如何执行这些特定步骤,那么您不知道如何使用您拥有的特定链接类。为了帮助您,我们需要查看其代码(如果它是现成的类,则需要查看其文档的链接)。
典型的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
}
你可以用这个:
void print(node* n) {
cout << n -> value << endl;
if(n -> next) print(n -> next);
}
并称之为:
int main() {
linked_list l;
...
print(l -> head);
return 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;
}
}